为什么这个递归函数在python中超过了最大长度?

时间:2017-11-04 21:13:10

标签: python list recursion

#finds length of a list recursively, don't understand why it exceeds maximum length, can someone please explain?
def lengtho(xs):

    if(xs == None):
        return 0
    return 1 + lengtho(xs[1:])


lengtho([1,2,3,4,1,4,1,4,1,1])

2 个答案:

答案 0 :(得分:4)

当代码到达列表末尾(基本情况)时,xs将等于[](空列表),而不是None。由于[][1:]只返回[],函数将调用自身直到堆栈溢出。 在python中编写这个函数的正确方法是:

def lengthof(xs):
   """Recursively calculate the length of xs.
      Pre-condition: xs is a list"""
   if (xs == []):
     return 0
   else:
     return 1+ lengthof(xs[1:])

答案 1 :(得分:2)

如果您正在谈论列表,那么递归的基本情况永远不会达到True值,xs == None将永远是False,可能您想要将其更改为xs == []或只是if not xs