[Python] What is the most efficient way to get length of path from adjacency matrix using...

Discussão em 'Python' iniciado por Stack, Abril 12, 2025.

  1. Stack

    Stack Membro Participativo

    The problem I am solving is optimizing a genetic algorithm for the Traveling Salesman Problem. Calculating the path takes the most time. Here is the current code I am working on:

    from itertools import pairwise
    import numpy as np
    from random import shuffle

    def get_path_len(adj_mat: np.ndarray, path: np.ndarray) -> float:
    return sum(adj_mat[i, j] for i, j in pairwise(path)) + adj_mat[path[-1], path[0]]

    mat = np.random.randint(1, 1000, (100, 100))
    path = np.asarray(list(range(100)))
    shuffle(path)

    print(get_path_len(mat, path))

    Continue reading...

Compartilhe esta Página