这个python代码的替代方案?
我不完全理解类中的一行代码,希望有更简单的替代方法。这样做的目的是,使用weightList,这是一个相互连接的边列表,并从图形(邻接矩阵)返回具有最低对应值的边列表。这是一个Prim的最小生成树问题这个python代码的替代方案?,python,sorting,minimum-spanning-tree,prims-algorithm,Python,Sorting,Minimum Spanning Tree,Prims Algorithm,我不完全理解类中的一行代码,希望有更简单的替代方法。这样做的目的是,使用weightList,这是一个相互连接的边列表,并从图形(邻接矩阵)返回具有最低对应值的边列表。这是一个Prim的最小生成树问题 edge=sorted(权重列表,key=lambda e:graph[e[0]][e[1]])[0]稍微分解一下就足够了。这个怎么样 get_edge_weight = lambda e: graph[e[0]][e[1]] sorted_weights = sorted(weightList,
edge=sorted(权重列表,key=lambda e:graph[e[0]][e[1]])[0]代码>稍微分解一下就足够了。这个怎么样
get_edge_weight = lambda e: graph[e[0]][e[1]]
sorted_weights = sorted(weightList, key=get_edge_weight)
edge = sorted_weights[0]
稍微分解一下就足够了。这个怎么样
get_edge_weight = lambda e: graph[e[0]][e[1]]
sorted_weights = sorted(weightList, key=get_edge_weight)
edge = sorted_weights[0]
完全按照你说的做:对于所有边,在图中找到最小的值
i, j = current_edge = weightList[0]
current_min = graph[i][j]
for edge in weightList[1:]:
i, j = edge
if graph[i][j] < current_min:
current_min = graph[i][j]
current_edge = edge
完全按照你说的做:对于所有边,在图中找到最小的值
i, j = current_edge = weightList[0]
current_min = graph[i][j]
for edge in weightList[1:]:
i, j = edge
if graph[i][j] < current_min:
current_min = graph[i][j]
current_edge = edge
如果您希望代码不那么“紧凑”,那么应该这样做:
shortest = weightList[0]
for edge in weightList:
if graph[edge[0]][edge[1]] < graph[shortest[0]][shortest[1]]:
shortest = edge
shortest=weightList[0]
对于权重列表中的边:
如果图[edge[0]][edge[1]<图[shortest[0]][shortest[1]]:
最短=边
将最短边设置为与权重列表中的第一条边相等,然后浏览列表,查看是否有任何边较短。如果希望代码稍微“紧凑”,这应该可以做到:
shortest = weightList[0]
for edge in weightList:
if graph[edge[0]][edge[1]] < graph[shortest[0]][shortest[1]]:
shortest = edge
shortest=weightList[0]
对于权重列表中的边:
如果图[edge[0]][edge[1]<图[shortest[0]][shortest[1]]:
最短=边
将最短边设置为与权重列表中的第一条边相等,然后浏览列表,查看是否有任何边较短。在尝试降低复杂性时,我总是想办法将内容分解为自解释的模块化函数:
def distance(adjacency_matrix, start_node, end_node):
return adjacency_matrix[start_node][end_node]
sorted_edges = sorted(weightList, key=lambda e: distance(graph, e[0], e[1]))
edge = sorted_edges[0];
当我试图降低复杂性时,我总是想办法将事情分解为自解释的模块化功能:
def distance(adjacency_matrix, start_node, end_node):
return adjacency_matrix[start_node][end_node]
sorted_edges = sorted(weightList, key=lambda e: distance(graph, e[0], e[1]))
edge = sorted_edges[0];
正是我需要的。代码现在有意义了。感谢我所需要的。这段代码现在有意义了。感谢您现在理解了这一行,这很好,但值得一提的是,这并不是一种特别有效的方法。您应该使用min
而不是sorted
。现在您能够理解这一行很好,但值得一提的是,这并不是一种特别有效的方法。您应该使用min
而不是sorted
。