递归调用未返回true到主算法函数(Python)

时间:2017-07-14 21:39:42

标签: python

这里有一个递归函数调用有点困难。这是一个汉密尔顿主义的路径算法,我正在尝试调试我的代码,但已达到死胡同。我在下面发布了我的代码,我的hamMain检查每个顶点,我的hamWalk遍历路径中尚未存在的顶点。

到目前为止,所有这些代码都很有用。我也会在下面发布一些调试代码。

一旦程序找到一个匹配(其中所采用的路径长度等于顶点的数量),它应该输出true给我的main,但它所做的只是转到hamMain中的下一个起始顶点。我认为这与我的程序的递归性质有关,并认为有更多经验的人可以推动我朝着正确的方向发展。

这是我的代码:

class HamProgram:
    def get_graph(self):
        adj_lines = []
        test = "input001.txt"
        with open(test, 'r') as adjFile:
        # with open(sys.argv[1], 'r') as adjFile:
            adjFile.readline()
            for line in adjFile:
                adj_lines.append(line.strip())
        G = nx.parse_adjlist(adj_lines, nodetype=int)
        return G

    def ham_walk(self, graph, path):
        k = len(path)
        print("current length of path")
        print(len(path))
        n = len(graph.nodes())
        print("Path")
        print(path)
        print("Neighbors")
        print(nx.neighbors(graph, path[-1]))
        if k == n:
            print("Here")
            return True
        for neighbor in nx.neighbors(graph, path[-1]):
            if neighbor not in path:
                print("Current neighbor")
                print(neighbor)
                path.append(neighbor)
                self.ham_walk(graph, path)
        return False

    def ham_main(self):
        graph = self.get_graph()
        print(graph.nodes())
        print(graph.edges())
        for node in graph.nodes():
            path = [node]
            if self.ham_walk(graph, path): #THIS DOESN'T PASS could it be with the self.ham_walk call?
                print("found path")
                output = "Hamiltonian Path: " + path
                break
            else:
                output = "False"
        return output

 class Main:
     execute = HamProgram()
     print(execute.ham_main())

这是一些调试证据,它找到了路径

   Current neighbor
   8
   current length of path
   9
   Path
   [0, 3, 6, 7, 4, 1, 2, 5, 8]

  [0]
  [0, 3]
  [0, 3, 6]
  [0, 3, 6, 7]
  [0, 3, 6, 7, 4]
  [0, 3, 6, 7, 4, 1]
  [0, 3, 6, 7, 4, 1, 2]
  [0, 3, 6, 7, 4, 1, 2, 5]
  [0, 3, 6, 7, 4, 1, 2, 5, 8]

这里应该返回true并打印路径,但它没有给出什么?

编辑:我已经标明了我认为问题所在。

由于

0 个答案:

没有答案