Skip to content
Advertisement

Iterate through an adjacency matrix with a list

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

The list items are pointing to row/column numbers.

So the 2nd row 4th col is:

JavaScript

and I would like to add them as:

JavaScript

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
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement