So I have a n x n adjacency matrix, N x N NumPy array, where the i-th row and the j-th column is the distance between the i-th and j-th cities.
I also have list, in a specific order in which I have to visit the cities and and add the distances together.
JavaScript
x
6
1
m = matrix
2
i = matrix_row
3
j = matrix_column
4
5
list = [1, 3, 4, 14, 26, 23...]
6
The list items are pointing to row/column numbers.
So the 2nd row 4th col is:
JavaScript
1
3
1
distance = m[3][14]
2
d = 124.9
3
and I would like to add them as:
JavaScript
1
2
1
m[list[0]][list[1]] + m[list[1]][list[2]] + m[list[2]][list[3]] and so on
2
How can I iterate through this?
Advertisement
Answer
You can use zip
and sum
as follows (or itertools.pairwise
instead of zip
in python 3.10+):
JavaScript
1
12
12
1
import numpy as np
2
3
m = np.reshape(range(9), (3, 3)) # an example matrix
4
print(m)
5
# [[0 1 2]
6
# [3 4 5]
7
# [6 7 8]]
8
9
lst = [0, 2, 1, 0]
10
total_dist = sum(m[i][j] for i, j in zip(lst, lst[1:]))
11
print(total_dist) # 12
12