我正在尝试计算列表的长度。当我在cmd上运行它时,我得到:
RuntimeError: maximum recursion depth exceeded in comparison
我不认为我的代码有什么问题:
def len_recursive(list):
if list == []:
return 0
else:
return 1 + len_recursive(list[1:])
不要使用递归,除非你可以预测它不会太深。 Python 对递归深度的限制很小。
如果你坚持递归,有效的方法是:
def len_recursive(lst):
if not lst:
return 0
return 1 + len_recursive(lst[1::2]) + len_recursive(lst[2::2])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)