简体   繁体   English

递归图遍历:如何生成和返回所有路径?

[英]Recursive graph traversal: how to generate and return all paths?

Here is my code right now: 现在是我的代码:

  hasht= {"A":["B", "D", "E"], "B":["C"], "C":["D", "E"], "D":["C", "E"], "E":["B"]}
   paths=[]
   def recusive(start, finish, val):
      if start==finish and val!=1:
        return start
    else:
        for i in hasht[start]:
            path= start+ recusive(i,finish,2)
            paths.append(path)
print (recusive("C","C",1))
print paths

Desired output: [CDC, CDEBC, CEBC] 所需输出: [CDC, CDEBC, CEBC]

I am trying to generate a table like the one above, but I am running into a problem where the string and the array are not being concatenated. 我正在尝试生成一个类似于上面的表,但是我遇到了一个问题,即字符串和数组未连接在一起。 When I just return, it returns CDC and works however and it exits the function as return is meant to do. 当我刚返回时,它返回CDC并可以工作,并且由于return的目的而退出了函数。 I am wondering how I can improve my code here to make it work and figure out why my logic was faulty. 我想知道如何在这里改善代码以使其正常工作,并弄清楚为什么我的逻辑有问题。 For example, I understand that it generates say [DC] , but I am confused as to how to go around that. 例如,我知道它生成说[DC] ,但是我对如何解决这个问题感到困惑。 Perhaps index the value returned? 也许索引返回的值? Yet that doesn't work either! 但这也不起作用! I am just confused as to how to make the path return once it is CDC , and then move on to the next one. 我只是对如何使路径返回为CDC之后感到困惑,然后继续进行下一个。

You need to be a little careful when using recursion in Python, as the pre-set limit on recursion depth is quite low, and you'll start getting errors like RuntimeError: maximum recursion depth exceeded in cmp if you recurse too deeply. 在Python中使用递归时,您需要格外小心,因为递归深度的预设限制非常低,并且您将开始遇到类似RuntimeError的错误如果递归得太深,将超出cmp中的最大递归深度

When I try to run your code, I get an error: TypeError: cannot concatenate 'str' and 'NoneType' objects . 当我尝试运行您的代码时,出现错误: TypeError:无法连接'str'和'NoneType'对象 This is because the function only returns a value when start == finish , ie when you get to 'C' again, in your example. 这是因为在示例中,该函数仅在start == finish时才返回值,即,当您再次到达“ C”时。 Because there is no return in the else part of the function, it returns the special value None , if start != end. 因为该函数的else部分没有返回 ,所以如果start!= end,它将返回特殊值None Python won't let you add None to a string, which explains the error. Python不允许您将None添加到字符串,这说明了错误。

The code below does what I think you're trying to do, which is return a list of all paths from startNode to endNode . 下面的代码完成了我认为您想要做的事情,即返回从startNodeendNode的所有路径的列表。 I've made the graph an input argument here, and the list of paths is returned. 我在这里将图作为输入参数,并返回路径列表。 It takes 2 additional arguments, allPaths and pathSoFar , to keep track of the list of all paths, and the current path. 它需要2个附加参数allPathspathSoFar ,以跟踪所有路径的列表以及当前路径。 This is only intended as an example of how to use recursion to achieve this. 这仅是作为如何使用递归来实现此目的的示例。 There are several things wrong with this code: 此代码有几处错误:

1) It uses recursion which, as I said earlier, is not a great idea in Python unless you increase the pre-set limit. 1)它使用了递归,正如我之前所说,除非增加预设限制,否则在Python中并不是一个好主意。

2) It does not deal properly with cycles. 2)不能正确处理循环。 If there are cycles in the graph, this function will just keep on going until it hits the recursion limit. 如果图中有循环,则此功能将继续进行直到达到递归限制。 Try running it with A as the start and end node to see this. 尝试以A作为起点和终点运行它以查看此情况。

    def generatePaths(theGraph, startNode, endNode, allPaths, pathSoFar=""):
        """
        Recursive function. Finds all paths through the specified
        graph from start node to end node. For cyclical paths, this stops
        at the end of the first cycle.
        """
        pathSoFar = pathSoFar + startNode

        for node in theGraph[startNode]:

            if node == endNode:
                allPaths.append(pathSoFar + node)
            else:
                generatePaths(theGraph, node, endNode, allPaths, pathSoFar)




    graph = {"A":["B", "D", "E"], "B":["C"], "C":["D", "E"], "D":["C", "E"], "E":["B"]}
    paths = []
    generatePaths(graph, "C", "C", paths)
    print paths

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM