Python 3.x 尝试返回路由具有多个值的最短路由
所以我可以返回一条路线,但它不是最短的。看起来代码似乎是在获取它所获得的第一个权重,而不是运行它们并反转以查看某些路由具有2个权重 我尝试过改变循环,但不断遇到错误,导致更多的问题,任何指导将是非常宝贵的 示例路线 a>b=800 b>e(有两个砝码,取更重的一个)=600500 最短总数-1300 然而,我得到1400,因为它需要更重的重量为b>EPython 3.x 尝试返回路由具有多个值的最短路由,python-3.x,graph,Python 3.x,Graph,所以我可以返回一条路线,但它不是最短的。看起来代码似乎是在获取它所获得的第一个权重,而不是运行它们并反转以查看某些路由具有2个权重 我尝试过改变循环,但不断遇到错误,导致更多的问题,任何指导将是非常宝贵的 示例路线 a>b=800 b>e(有两个砝码,取更重的一个)=600500 最短总数-1300 然而,我得到1400,因为它需要更重的重量为b>E # Dictionaries are a convenient way to store data for later retrieval b
# Dictionaries are a convenient way to store data for later retrieval by name (key)
class Graph:
def __init__(self):
"""
self.edges is a dict of all possible next nodes
e.g. {'X': ['A', 'B', 'C', 'E'], ...}
self.weights has all the weights between two nodes,
with the two nodes as a tuple as the key
e.g. {('X', 'A'): 7, ('X', 'B'): 2, ...}
"""
self.edges = defaultdict(list)
self.weights = {}
def add_edge(self, from_node, to_node, weight):
# This should assume that the edges are bidirectional
self.edges[from_node].append(to_node)
self.edges[to_node].append(from_node)
self.weights[(from_node, to_node)] = weight
self.weights[(to_node, from_node)] = weight
graph = Graph()
edges = [
('A', 'B', 800),
('B', 'C', 900),
('C', 'D', 400),
('D', 'E', 400),
('B', 'F', 400),
('C', 'E', 300),
('D', 'E', 300),
('E', 'B', 600),
('C', 'E', 200),
('D', 'C', 700),
('E', 'B', 500),
('F', 'D', 200),
]
for edge in edges:
graph.add_edge(*edge)
def dijsktra(graph, initial, end):
# shortest paths is a dict of nodes
# whose value is a tuple of (previous node, weight)
shortest_paths = {initial: (None, 0)}
current_node = initial
visited = set()
# if not initial or not end:
# return print('No flight path provided')
while current_node != end:
visited.add(current_node)
destinations = graph.edges[current_node]
weight_to_current_node = shortest_paths[current_node][1]
for next_node in destinations:
weight = graph.weights[(current_node, next_node)] + weight_to_current_node
if next_node not in shortest_paths:
shortest_paths[next_node] = (current_node, weight)
else:
current_shortest_weight = shortest_paths[next_node][1]
if current_shortest_weight > weight:
shortest_paths[next_node] = (current_node, weight)
next_destinations = {node: shortest_paths[node] for node in shortest_paths if node not in visited}
if not next_destinations:
return "Route Not Possible"
# next node is the destination with the lowest weight
current_node = min(next_destinations, key=lambda k: next_destinations[k][1])
# Work back through destinations in shortest path
path = []
while current_node is not None:
path.append(current_node)
next_node = shortest_paths[current_node][0]
current_node = next_node
# Reverse path
path = path[::-1]
return path