Better equivalent of this crazy nested python for loop

天涯浪子 提交于 2019-12-05 04:02:35
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)

This is a classical recursive problem. Your function should returns concatenation of node value with all results of your function result for each child node. As you can see in sentence, function behavior is explained in a recursive way:

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 )

Result:

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

This code is a start point. You can store all paths in a list, use yield generator, etc. Don't forget to prevent circles.

Also, take a look to igraph solution. Sure this library can helps to you, see this example: Finds all shortest paths (geodesics) from a vertex to all other vertices.

Regards.

Just like other suggested, with recursion:

    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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!