2024-10-01 22:29:37 发布
网友
#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])
当代码到达列表的末尾(基本情况)时,xs将等于[](空列表),而不是None。因为[][1:]只是返回[],所以函数将调用自身直到堆栈溢出。 用python编写此函数的正确方法是:
xs
[]
None
[][1:]
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
True
xs == None
False
xs == []
if not xs
当代码到达列表的末尾(基本情况)时,
xs
将等于[]
(空列表),而不是None
。因为[][1:]
只是返回[]
,所以函数将调用自身直到堆栈溢出。 用python编写此函数的正确方法是:递归的基本情况永远不会达到
True
值,xs == None
将始终是False
如果您谈论的是列表,可能您希望将其更改为xs == []
或只是if not xs
相关问题 更多 >
编程相关推荐