【问题标题】:Using nested dictionaries to store user defined graph使用嵌套字典存储用户定义的图形
【发布时间】: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


【解决方案1】:

你真的只希望用户每条边输入一次,那么你可以只存储两次。

edges = {}
while True:
    edge = input('Enter an edge as Node names separated by a space followed by a number ("exit" to exit): ')
    if edge == 'exit':
        break
    node1, node2, weight = edge.split()
    weight = float(weight)
    if node1 not in edges:
        edges[node1] = {}
    if node2 not in edges:
        edges[node2] = {}
    edges[node1][node2] = weight
    edges[node2][node1] = weight

用户以"A B 3.5"的身份输入每条边一次

【讨论】:

    【解决方案2】:

    Khanacademy 有一个非常好的页面,介绍了不同的图表表示方式。

    对于无向图(a => b 和 b => a),我个人会考虑使用边列表。可以排序提高查找效率,而且比邻接表等其他方法更节省内存

    【讨论】:

      猜你喜欢
      • 2019-04-07
      • 2019-09-17
      • 2017-01-19
      • 2015-06-28
      • 1970-01-01
      • 2015-07-03
      • 1970-01-01
      • 2021-06-16
      • 1970-01-01
      相关资源
      最近更新 更多