在另一个函数(Python)

时间:2017-07-14 16:52:07

标签: python function

我正在为一个项目写一个算法(我确定我的代码中的其他地方有错误,但我不会帮助我,因为我将在稍后处理这些错误)。但我遇到了基本的python组织错误。基本上我使用了一个库(networkX),并且有一个功能齐全的图形(我已经测试过了,节点和边缘)。我遇到了如何设置参数然后实际执行ham_main()函数的错误。

def ham_walk(self, graph, path):
    if len(path) == len(graph.nodes()):
        return True
    for neighbor in graph.neighbors(path.pop()):
        if neighbor not in path:
            ham_walk(graph, path.append(neighbor))
    return False

def ham_main(self):
    graph = self.getGraph()
    print(graph.nodes())
    print(graph.edges())
    path = []
    for node in graph.nodes():
        path = [node]
        if ham_walk(self, graph, path):
            return print("Hamiltonian Path: " + path)
        else:
            print("False")
            return False
    return print("Hamiltonian Path: " + path)
  class Main:
      execute = HamParser()
      execute.ham_main()

当我尝试在我的主类中执行时,我收到以下错误;

      File "C:/Users/Chris/Dropbox/HamProgram.py", line 33, in ham_main
       if ham_walk(self, graph, path):
       NameError: name 'ham_walk' is not defined

似乎ham_walk没有注册。我错过了一些重要的东西吗?

编辑:完整代码

from sys import argv
import networkx as nx


class HamParser:

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

    def ham_walk(self, graph, path):
        if len(path) == len(graph.nodes()):
            return True
        for neighbor in graph.neighbors(path.pop()):
            if neighbor not in path:
                ham_walk(graph, path.append(neighbor))
        return False

    def ham_main(self):
        graph = self.getGraph()
        print(graph.nodes())
        print(graph.edges())
        path = []
        for node in graph.nodes():
            path = [node]
            if ham_walk(self, graph, path):
                return print("Hamiltonian Path: " + path)
            else:
                print("False")
                return False
        return print("Hamiltonian Path: " + path)


class Main:
    execute = HamParser()
    execute.ham_main()

3 个答案:

答案 0 :(得分:1)

您的问题在这里:

if ham_walk(self, graph, path):

您不需要将自身作为参数传递,ham_walk的定义 知道要引用哪个对象实例。只需将其更改为:

if self.ham_walk(graph, path):

答案 1 :(得分:1)

您可以尝试这种方式:

from sys import argv
import networkx as nx


class HamParser:

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

    def ham_walk(self, graph, path):
        if len(path) == len(graph.nodes()):
            return True
        for neighbor in graph.neighbors(path.pop()):
            if neighbor not in path:
                self.ham_walk(graph, path.append(neighbor))
        return False

    def ham_main(self):
        graph = self.getGraph()
        print(graph.nodes())
        print(graph.edges())
        path = []
        for node in graph.nodes():
            path = [node]
            if self.ham_walk(self, graph, path):
                return print("Hamiltonian Path: " + path)
            else:
                print("False")
                return False
        return print("Hamiltonian Path: " + path)


class Main:
    execute = HamParser()
    execute.ham_main()

答案 2 :(得分:1)

来自sys import argv 将networkx导入为nx

班级HamParser:

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

def ham_walk(self, graph, path):
    if len(path) == len(graph.nodes()):
        return True
    for neighbor in graph.neighbors(path.pop()):
        if neighbor not in path:
            self.ham_walk(graph, path.append(neighbor))
    return False

def ham_main(self):
    graph = self.getGraph()
    print(graph.nodes())
    print(graph.edges())
    path = []
    for node in graph.nodes():
        path = [node]
        if self.ham_walk(graph, path):
        # NOT if self.ham_walk(self, graph, path):
        # self is bound as first arg when HamPath() is instantiated.
        #     by putting self in the call again, you are basically passing self in a second time, and calling ham_walk with a second "self" where graph should be. 
        #  in this case, it will throw error b/c number of args (3) does not match signature (2)
            return print("Hamiltonian Path: " + path)
        else:
            print("False")
            return False
    return print("Hamiltonian Path: " + path)

班级主要:     execute = HamParser()     execute.ham_main()