给定一个加权有向图和一个定义为“目的地”的特定节点,我试图找到从每个节点到目的地的最短路径上的第一个链接。为了实现这个目标,我首先尝试了以下代码。在
import networkx as nx
import numpy as np
def choose_nextlink(graph, current_node, destination):
path_shortest = nx.shortest_path(graph, source=current_node, target=destination)
return path_shortest[0:2]
def main():
nodes = np.array([1, 2, 3, 4])
destinations = np.array([4])
edges = np.array([[1, 2], [1, 4], [2, 3], [3, 4]])
weights = np.array([1, 10, 2, 3])
G = nx.DiGraph()
G.add_nodes_from(nodes)
G.add_weighted_edges_from(np.hstack([edges, np.array([weights]).transpose()]))
links_next = np.fromfunction(lambda i, j: choose_nextlink(G, current_node=np.setdiff1d(nodes, destinations)[i], destination=4)[j], (np.setdiff1d(nodes, destinations).shape[0], 2))
if __name__ == '__main__':
main()
在上面定义的图中,从节点1、2和3到节点4的最短路径为
所以我希望links_next
成为
但是,由python3 test.py
运行此脚本会出现错误:
Traceback (most recent call last):
File "test.py", line 24, in <module>
main()
File "test.py", line 20, in main
links_next = np.fromfunction(lambda i, j: choose_nextlink(G, current_node=np.setdiff1d(nodes, destinations)[i], destination=4)[j], (np.setdiff1d(nodes, destinations).shape[0], 2))
File "/usr/local/lib/python3.5/site-packages/numpy/core/numeric.py", line 2132, in fromfunction
return function(*args, **kwargs)
File "test.py", line 20, in <lambda>
links_next = np.fromfunction(lambda i, j: choose_nextlink(G, current_node=np.setdiff1d(nodes, destinations)[i], destination=4)[j], (np.setdiff1d(nodes, destinations).shape[0], 2))
IndexError: arrays used as indices must be of integer (or boolean) type
在google上搜索了一下这个错误之后,似乎在v1.12.0中引入了these changes,但我还没有找到解决方案。我认为第20行中的所有索引(变量i
和{0
)都是整数类型。在
当然,我可以使用for
循环来完成相同的任务,但我希望避免这种方法,因为我的实际数据集很大。我在哪里把上面的代码弄错了?在
目前没有回答
相关问题 更多 >
编程相关推荐