在python中使用列表进行递归 [英] recursion with a list in python
问题描述
我刚刚开始学习python,有些递归问题似乎无法解决.最烦人的是:我需要构建一个函数 ind(e,L)
,其中 e
是一个int值,而 L
是一个列表.
I just started learning python and there are some recursion questions that I can't seem to figure out. The most annoying one is this:
I need to build a function ind(e,L)
where e
is an int and L
is a list.
通过输入 e
(如果它在列表中),需要将输出作为其索引例如:
By entering e
if it is in the list the output needs to be its index
For example:
ind(42,[0,14,52,42,15]) -> 3
这是我到目前为止编写的代码,但是我得到的索引始终为0.有人可以向我解释我做错了什么吗?
This is the code I wrote this far but the index I get is always 0. Can someone please explain to me what I am doing wrong?
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.
You only return if e
is at index 0 (you can skip the L[:-1]...
term, it is always 0) and propagate that unchanged. Instead of returning the meaningless index, return the number of recursions. The simplest way is to add 1 whenever the function recurses.
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:])
这篇关于在python中使用列表进行递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!