【问题标题】:What is wrong with my function? Finding the shortest path using numpy and networkx我的功能有什么问题?使用 numpy 和 networkx 查找最短路径
【发布时间】:2026-01-04 08:20:03
【问题描述】:

所以我正在创建一个代码来使用 networkx 计算最短路径。我使用 numpy 创建了一个 3D 数组,然后像这样计算最短路径:

import numpy as np
import networkx as nx

arr = np.random.randint(1, 100, size = (2, 5, 5)) #3D array

for i in arr:
    graph = nx.from_numpy_array(i, create_using = nx.DiGraph)
    path = nx.shortest_path(graph, 0, 3, weight = 'weight')
    print(path)

由于我使用的是两个矩阵,我得到了下一个输出:

[0, 1, 3] #path1
[0, 3]    #path2

之后我决定创建一个函数来做同样的事情,就像这样:

import numpy as np
import networkx as nx

arr = np.random.randint(1, 100, size = (2, 5, 5)) #3D array


def shortest(prices):

    for i in arr:
        graph = nx.from_numpy_array(i, create_using = nx.DiGraph)
        path = nx.shortest_path(graph, 0, 3, weight = 'weight')
        return path

print(shortest(arr))

我得到了下一个输出:

[0, 1, 3] #same as path 1

如果我像这样改变“返回路径”的位置:

def shortest(precios):

    for i in arr:
        graph = nx.from_numpy_array(i, create_using = nx.DiGraph)
        path = nx.shortest_path(graph, 0, 3, weight = 'weight')
    return path

print(shortest(arr))

我得到了下一个输出:

[0, 3] #same as path 2

我无法使用我的函数在同一输出中获取两条路径。知道这里发生了什么吗?我正在练习在 python 中使用函数,因为我对这个主题有点陌生,所以我希望你能帮助我看看有什么问题?谢谢!

【问题讨论】:

    标签: python function numpy for-loop networkx


    【解决方案1】:

    这与networkxnumpy无关;这是简单的控制流程。您的“最短路径”循环遍历提供的图表并找到每个图表的最短路径。

    非函数版本会打印找到的每条路径——仍然一次只处理一个。由于您在函数中没有规定聚合找到的解决方案,因此您一次仍然只能得到一个......对于函数来说,这意味着您只能得到一个。

    此代码在找到第一个解决方案后立即返回:

    for i in arr:
        graph = nx.from_numpy_array(i, create_using = nx.DiGraph)
        path = nx.shortest_path(graph, 0, 3, weight = 'weight')
        return path   # The function ends as soon as it gets here: you get only the first solution.
    

    这段代码找到了所有的解决方案,但你一找到下一个就扔掉一个:

    for i in arr:
        graph = nx.from_numpy_array(i, create_using = nx.DiGraph)
        path = nx.shortest_path(graph, 0, 3, weight = 'weight')
        # You just deleted the previous solution, and replaced it with another.
    
    return path
    

    这仅返回 last 解决方案,因为这是您唯一没有覆盖的解决方案。您必须以某种方式累积解决方案并将它们一起返回,或者更改您的函数用法。例如:

    all_path = []
    for i in arr:
        graph = nx.from_numpy_array(i, create_using = nx.DiGraph)
        all_path.append( nx.shortest_path(graph, 0, 3, weight = 'weight') )
    
    return all_path
    

    【讨论】:

    • 哦!我明白了,所以我创建了一个新列表并存储了解决方案!非常感谢!
    最近更新 更多