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

2024-10-01 22:29:37 发布

您现在位置:Python中文网/ 问答频道 /正文

#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])

Tags: ofreturnitcanlengthlistrecursivelyfinds
2条回答

当代码到达列表的末尾(基本情况)时,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:])

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

相关问题 更多 >

    热门问题