这段代码有什么问题?

时间:2014-10-19 23:54:20

标签: python

这个问题更多的是关于理解我编译的代码中出了什么问题。

基本上,此代码会计算并告诉您一个人拥有的后代数量。

class Person:
    """Person class.

    Attributes:
    - name (str): The name of this Person
    - children (list of Person): a list of the Person objects who
                             are the children of this Person
    """

    def __init__(self, name):
        """ (Person, str) -> NoneType
        Create a new person with the given name, and no children.
        """
        self.name = name
        self.children = []
        i = 0
        self.l = self.children

    def recur(l):
        if not l:
            return 0
        else:
            return recur(l[1:]) + len(l[0])

    def count_descendants(self):
        """ (Person) -> int
        Return the number of descendants of self.
        """
        children = self.children

        recur(children)

我收到了一个名称错误:

NameError: name 'recur' is not defined

1 个答案:

答案 0 :(得分:1)

您根本不需要recur()功能,因为所有count_descendants()都会调用它。您对后代数量的计算也是不正确的。

以下是代码的简化版本:

#!/usr/bin/env python 

class Person:
    def __init__(self, name):
        self.name = name
        self.children = []

    def count_descendants(self):
        if not self.children:
            return 0
        else:
            n = len(self.children)
            for kid in self.children:
                n += kid.count_descendants()
            return n

a = Person('a')
b = Person('b')
c = Person('c')
d = Person('d')
e = Person('e')
f = Person('f')
g = Person('g')
h = Person('h')

a.children = [b, c, d]
b.children = [e]
c.children = [f, g]
f.children = [h]

for p in [a, b, c, d, e, f, g, h]:
    print p.name + ' has ' + str(p.count_descendants()) + ' descendants'

输出:

paul@thoth:~/src/sandbox$ ./desc.py
a has 7 descendants
b has 1 descendants
c has 3 descendants
d has 0 descendants
e has 0 descendants
f has 1 descendants
g has 0 descendants
h has 0 descendants
paul@thoth:~/src/sandbox$ 

一个人拥有的后代数是自己孩子的数量,加上所有孩子后代的总和。每个孩子的后代的数量是它的自己孩子的数量,加上......的总和......等等。这是你获得递归的地方。上面修订的count_descendants()方法实现了这种算法。