我刚开始学习python,有一些递归问题我似乎无法弄清楚。最烦人的是这个:
我需要构建一个函数ind(e,L)
where e
是一个整数并且L
是一个列表。
通过输入e
如果它在列表中,则输出需要是它的索引
例如:
ind(42,[0,14,52,42,15]) -> 3
这是我到目前为止编写的代码,但我得到的索引始终为 0。有人可以向我解释我做错了什么吗?
def location(e,L):
if L == []:
return False
elif e == L[0]:
A = L[:-1].index(e)
return A
else:
return location(e,L[1:])
print(location(14,[1,2,14,1]))
谢谢 :)
您只有在以下情况下才返回e
位于索引 0(您可以跳过L[:-1]...
项,它始终为 0) 并传播不变。不返回无意义的索引,而是返回递归次数。最简单的方法是每当函数递归时就加 1。
def location(element, sequence):
if not sequence:
# e is not in the list at all
# it is not meaningful to return an index
raise IndexError
elif element == sequence[0]:
# we already know where e is
# since we checked it explicitly
return 0
else:
# keep searching in the remainder,
# but increment recursion level by 1
return 1 + location(element, sequence[1:])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)