mic*_*ox2 5 python recursion list python-3.x
我刚开始学习 python 并且有一些我似乎无法弄清楚的递归问题。最烦人的是:我需要构建一个函数ind(e,L)
,其中e
是一个 int 并且L
是一个列表。
通过输入e
它是否在列表中,输出需要是它的索引 例如:
ind(42,[0,14,52,42,15]) -> 3
Run Code Online (Sandbox Code Playgroud)
这是我到目前为止编写的代码,但我得到的索引始终为 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]))
Run Code Online (Sandbox Code Playgroud)
谢谢 :)
仅当 is 位于索引 0 时才返回e
(您可以跳过该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:])
Run Code Online (Sandbox Code Playgroud)