【问题标题】:Better equivalent of this crazy nested python for loop更好地等效于这个疯狂的嵌套 python for 循环
【发布时间】:2012-02-12 22:46:38
【问题描述】:
for a in map:
    for b in map[a]:
        for c in map[b]:
            for d in map[c]:
                for e in map[d]:
                    print a+b+c+d+e

以上代码用于在图中创建一定长度的所有路径。 map[a] 表示从 a 点可以到达的点。

如何更改它以模拟任意数量的循环?

这就像一个笛卡尔积 (itertools.product),在每次迭代中 您对下一个元素的选择仅限于 map[current_point] 中的元素。

【问题讨论】:

  • 嗯,你已经用递归标记了它。你试过了吗?

标签: python recursion generator nested-loops


【解决方案1】:
map = {
    'a': ['b', 'c'],
    'b': ['c', 'd'],
    'c': ['d', 'a'],
    'd': []
}

def print_paths(map, start, length, prefix = ''):
    if length == 0:
        print prefix
    else:
        for a in map[start]:
            print_paths(map, a, length - 1, prefix + start)

for a in map.keys():
    print_paths(map, a, 5)

【讨论】:

  • 对不起,我忘了说 map[a][b] 是一个整数,表示 a 到 b 之间的距离。因此,您的解决方案一旦达到整数就会停止工作。您能告诉我如何将其更改为与嵌套循环完全相同的内容吗?所以这个函数不会超出 map[a]。 (map[X] 对于任何给定的点 X 都足够了,因为您选择从某个点下一步可以去哪里并不取决于您是如何到达那里的)
  • 如果 map[a][b] 是整数,则您的原始代码无法运行。您能否用map 的工作示例更新问题?我会在这个答案中添加我假设的map
  • ...并编辑答案以使其真正起作用,因为我和 5 位支持者都没有注意到它没有...
【解决方案2】:

这是一个经典的递归问题。您的 function 应该返回节点值与每个子节点的 function 结果的所有结果的串联。正如你在句子中看到的那样,函数行为是以递归方式解释的:

myGraph = { 1:[2,3], 2:[3,4] }

def recorre( node_list, p = '' ):    
    for node in node_list:
        if node in myGraph and myGraph[node]: 
            recorre(myGraph[node], p+unicode( node ))
        else:
            print p+unicode( node )

recorre( myGraph )

结果:

>>> recorre( myGraph )
123
124
13
23
24

此代码是一个起点。您可以将所有路径存储在列表中,使用yield 生成器等。不要忘记防止圈子。

另外,看看igraph solution。当然这个库可以帮助你,看这个例子:Finds all shortest paths (geodesics) from a vertex to all other vertices

问候。

【讨论】:

    【解决方案3】:

    就像其他建议一样,使用递归:

        distances = []        
    
        def compute_distance(map, depth, sum):
             if depth == 0 or len(map) == 0:
                distances.append[sum]
             else:
                for a in map:
                   compute_distance(map[a], depth - 1, sum + a)
    
       compute_distance(map, x, 0)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-20
      • 2020-06-07
      • 2019-04-15
      相关资源
      最近更新 更多