为什么这个递归函数超过了python中的最大长度?
当代码到达列表末尾时(基本情况),为什么这个递归函数超过了python中的最大长度?,python,list,recursion,Python,List,Recursion,当代码到达列表末尾时(基本情况),xs将等于[](空列表),而不是None。由于[][1:]只返回[],因此函数将调用自身,直到堆栈溢出。 用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): r
xs
将等于[]
(空列表),而不是None
。由于[][1:]
只返回[]
,因此函数将调用自身,直到堆栈溢出。
用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])
您的递归基本情况永远不会达到
True
值,xs==None
将始终是False
如果您谈论的是列表,可能您想将其更改为xs=[]
,或者如果不是xs,[]
与None
不一样。谢谢,我还不熟悉python语法如果不是xs:
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:])