Python中for循环的递归函数

时间:2017-12-10 15:32:43

标签: python function recursion

我正在尝试在Python中执行递归函数,以使所有父母从给定的孩子开始 - 例如。如果我想找到所有父母从A开始 - A有父母B和C,B有父母D和E,C有父母F和G,所以函数应该返回集:{B,C,D,E,F, G} 我有一个类GenTree,我将所有人保存在self.people(实例,而不是名称)和类Person中,它具有方法get_parents()以返回False或父类的元组(类Person的2个实例)< / p>

以下是包含类和方法的整个文件:

class Person:
    def __init__(self, name, gender, education, father = False, mother = False):
        self.name = name
        self.gender = gender
        self.education = education
        self.father = father
        self.mother = mother
        self.children = []
    def add_parent(self, inst):
        if inst.gender=="m":
            self.father = inst
        else:
            self.mother = inst
    def add_child(self, inst):
        self.children.append(inst)
    def has_parent(self):
        return True if self.father or self.mother else False
    def get_parents(self):
        if self.has_parent():
            if self.father and self.mother: return self.father, self.mother
            if self.father and not self.mother: return self.father
            if self.mother and not self.father: return self.mother
        else:
            return ()

class GenTree:
    def __init__(self):
        self.people = {}
    def load_from_file(self, file_name):
        data = open(file_name, "r")
        people = {}
        reading = "person"
        for line in data:
            line = line.rstrip()
            reading = "fam" if line=="" else reading
            if reading=="person":
                thisInfo = line.split(";")
                thisName = thisInfo[0]
                thisGender = thisInfo[1]
                thisEd = thisInfo[2]
                self.people[thisName] = Person(thisName, thisGender, thisEd)
            else:
                if line == "":
                    continue
                thisInfo = line.split("=>")
                for i in range(len(thisInfo)):
                    thisInfo[i] = thisInfo[i].rstrip()
                    thisInfo[i] = thisInfo[i].strip(" ")
                self.people[thisInfo[1]].add_parent(self.people[thisInfo[0]])
                self.people[thisInfo[0]].add_child(self.people[thisInfo[1]])

    def get_all_parents(self, child_name):
        child = self.people[child_name]
        parents = child.get_parents()
        if parents:
            for parent in parents:
                return parents + self.get_all_parents(parent.name)
        return parents

g = GenTree()
g.load_from_file("data_a")
print([i.name for i in g.get_all_parents('Katka')])

以下是包含给定数据的文件:

Ales;m;c
Alexandr;m;c
Anna;f;h
Dana;f;e
Daniela;f;u
David;m;u
Hana;f;h
Jana;f;u
Jarda;m;c
Jindra;m;u
Jirka;m;u
Jitka;f;h
Juraj;m;u
Karel;m;e
Katka;f;c
Lenka;f;h
Leon;m;h
Leona;f;c
Leos;m;e
Lida;f;e
Ludmila;f;h
Magdalena;f;c
Matej;m;u
Michaela;f;h
Michal;m;e
Patricia;f;h
Petr;m;h
Richard;m;e
Sasa;f;u
Stefan;m;h
Tereza;f;h
Tomas;m;e
Vaclav;m;e
Vojtech;m;c
Zdena;f;e
Zdenek;m;h

Ales        => Zdenek
Tereza      => Zdenek
Alexandr    => Vojtech
Zdena       => Vojtech
David       => Anna
Sasa        => Anna
Jarda       => Daniela
Patricia    => Daniela
Vojtech     => Jindra
Daniela     => Jindra
Zdenek      => Jirka
Anna        => Jirka
Vaclav      => Juraj
Michaela    => Juraj
Ales        => Ludmila
Tereza      => Ludmila
Ludmila     => Magdalena
Juraj       => Magdalena
Juraj       => Tomas
Anna        => Tomas
Zdenek      => Lida
Sasa        => Lida
Lida        => Leona
Zdenek      => Leona
Tomas       => Stefan
Anna        => Stefan
Tomas       => Karel
Leona       => Karel
Tomas       => Leos
Leona       => Leos
Tomas       => Lenka
Leona       => Lenka
Juraj       => Matej
Lenka       => Matej
Juraj       => Leon
Anna        => Leon
Juraj       => Richard
Lenka       => Richard
Richard     => Petr
Ludmila     => Petr
Petr        => Michal
Dana        => Michal
Stefan      => Dana
Anna        => Dana
Michal      => Hana
Lida        => Hana
Michal      => Jana
Lida        => Jana
Petr        => Jitka
Dana        => Jitka
Jirka       => Katka
Dana        => Katka

现在,“print([i.name for i in g.get_all_parents('Katka')])”应该返回:

{'Jirka', 'Dana', 'Zdenek', 'Anna', 'Stefan', 'Ales', 'Tereza', 'David', 'Sasa', 'Tomas', 'Juraj', 'Vaclav', 'Michaela'}

但它返回

['Jirka', 'Dana', 'Zdenek', 'Anna', 'Ales', 'Tereza']

但它始终只为for循环中的第一个“self.get_all_parents(parent.name)” 另外,我不知道如何将它作为一个集合返回(我试图做get_all_parents(self,child_name,allparents = set()),但它似乎没有重置每次调用函数设置的allparents)< / p>

1 个答案:

答案 0 :(得分:0)

在大多数情况下,使用带有递归的for循环并不是一个好主意。实际上它们有点相同。 Haskell(函数式编程语言)没有for循环

def get_all_parents(self, child_name):
        child = self.people[child_name]
        parents = child.get_parents()
        if parents:
            return parents + self.get_all_parents(parent[0].name) + self.get_all_parents(parent[1].name)

        return parents

简单的递归调用意味着自己调用一次或多次

return parents + self.get_all_parents(parent[0].name) + self.get_all_parents(parent[1].name)

此处get_all_parents会将其正确的值返回到+ ....

修改

你可以在特殊情况下使用for循环。但是这种编码可能非常令人困惑且难以推理

def get_all_parents(self, child_name , ret = ()):
    child = self.people[child_name]
    parents = child.get_parents()
    if parents:
        for p in parents:
            ret = self.get_all_parents(p.name , ret)
    return parents + ret

在这种情况下,我们需要一个额外的对象在每次调用之间传递并将结果添加到它。它类似于所有函数调用之间的共享对象。 你可以轻松转一个列表来设置这个问题已经回答了看看How to construct a set out of list items in python?