【发布时间】:2016-10-18 15:39:51
【问题描述】:
我试图让用户手动输入图表,而不是在代码中使用“预先存在”的图表,以便在我的 Dijkstra 算法中使用。
我已经完成了这项工作,但希望得到一些关于其实施和用户友好性的反馈。此外,是否有更有效的方式将图形输入嵌套字典?如果有怎么办?
关于代码的要点
- 数据必须使用嵌套字典存储
- 循环将为零,例如 b-b 为 0 不留空,但这仅在用户图中存在循环时才会发生,否则将被忽略。
- 理想情况下,我不想在自己编码之前使用现有库中的任何内容,以便更好地了解正在发生的事情
非常感谢。 编辑:不再需要重复要求。
{'A': {'C': 1, 'B': 5}, 'D': {}, 'B': {'D': 2}, 'C': {'D': 9}}
^ 节点的期望输出也是当前输出。
nodes = {}
def add_node():
entered_graph = False
while not entered_graph:
source_node = input("Enter a source node: ")
num_neighbours = int(input("Enter how many neighbours this node has"
"including previously entered nodes: "))
nodes[source_node] = {}
for neighbour in range(num_neighbours):
neighbour = input("Enter neighbor node: ")
distance = int(input("Enter distance from source node to this neighbor node: "))
nodes[source_node][neighbour] = distance
end_loop = input("Enter y to finish graph entry: ")
end_loop = end_loop.lower()
if end_loop == "y":
entered_graph = True
add_node()
print(nodes)
【问题讨论】:
-
“数据必须使用嵌套字典存储”为什么?我会创建一个以元组为键的字典
(from_location_id, to_location_id)。 -
特别是如果您说这是一个对称图,例如 a-->b == b-->a。然后,您只需要存储其中一对并测试两者,即 (a, b) 或 (b, a)。这对于内存方面的大问题非常重要。将单个位置作为键的嵌套字典会导致不必要的大量重复。
-
确实我已经在我的算法中纠正了这一点,所以现在不需要添加每个弧两次。
标签: python dictionary