图/树在Koenigsberg的蟒蛇桥中行走

时间:2015-10-12 08:04:48

标签: python graph tree

给出以下图表(来自Koenigsberg问题的桥梁)

graph = { "a" : ["c", "d"],
          "b" : ["c", "d"],
          "c" : ["a", "b", "d"],
          "d" : ["a", "b", "c"]
        }

我正在尝试创建一个循环,其中n次迭代对应于给定特定开始点头的步行长度。

从节点a开始说一个长度为2的步行,我们应该得到类似的东西:

[["c", "d"],["a", "b", "d","a", "b", "c"], ["c", "d","c", "d","a", "b", "c","c", "d","c", "d","a", "b", "d"]]

首先,我需要将链接附加到起始节点的每个元素以进入树的下一级。

我尝试了以下内容。

stnode = "a"
walk = list()
walk.append(graph[stnode])

for i in graph [stnode]:
    walk.append(graph[i])
    print walk

返回

[['c', 'd'], ['a', 'b', 'd']]
[['c', 'd'], ['a', 'b', 'd'], ['a', 'b', 'c']]

但我只需要

[['c', 'd'], ['a', 'b', 'd'], ['a', 'b', 'c']]

1 个答案:

答案 0 :(得分:1)

问题是您只创建一个列表,并附加到该列表。 相反,您应该有一个主walk列表,您还应该为每个级别创建一个新列表,使用图中的任何内容扩展它,然后将该列表附加到main步行列表

stnode = "a"
walk = list()
walk.append(graph[stnode])

next_walk = list()
for i in graph [stnode]:
    next_walk.extend(graph[i])
walk.append(next_walk)
print walk

以下是您可以一次完成所有操作的方法:

walk_len = 2
start_node = 'a'
walk = [[start_node]]
for _ in range(walk_len+1):
    next_nodes = list()
    for node in walk[-1]:
        next_nodes.extend(graph[node])
    walk.append(next_nodes)
walk = walk[1:]