Python递归和列表
我正在学习python中的递归,我有以下代码:Python递归和列表,python,recursion,Python,Recursion,我正在学习python中的递归,我有以下代码: def search(l,key): """ locates key in list l. if present, returns location as an index; else returns False. PRE: l is a list. POST: l is unchanged; returns i such that l[i] == key; False otherwise. ""
def search(l,key):
"""
locates key in list l. if present, returns location as an index;
else returns False.
PRE: l is a list.
POST: l is unchanged; returns i such that l[i] == key; False otherwise.
"""
if l: # checks if list exists
if l[0] == key: # base case - first index is key
return True
s = search(l[1:], key) # recursion
if s is not False:
return s
return False # returns false if key not found
有人能给我解释一下线路是什么吗
s = search(l[1:], key)
确实如此吗?l[1:]对列表做了什么?它递归调用
搜索
函数,使用l
中的切片数据l[1::
表示索引1
之前不包括元素的所有数据。比如说,
data = [1, 2, 3, 4, 5]
print data[1:] # [2, 3, 4, 5]
print data[2:] # [3, 4, 5]
例如,可以使用切片表示法获取范围之间的值
print data[1:4] # [2, 3, 4]
print data[2:3] # [3]
您还可以获取特定索引之前的所有元素(不包括索引处的元素)
有时,您可能从末尾就不知道元素的索引。所以,你可以使用负指数,像这样
print data[-2:] # [4, 5]
print data[1:-2] # [2, 3]
print data[:-3] # [1, 2]
使用负索引时,最后一个元素用
-1
表示,最后一个元素用-2
表示,依此类推。您可以在此中阅读有关此切片符号的更多信息函数编程语言中递归遍历列表的常用方法是使用访问列表第一个元素的函数(名为car
,first
,head
,具体取决于语言)以及另一个访问列表其余部分的函数(cdr
,rest
,tail
)。在Python中,没有与这些函数直接等效的函数,但我们可以使用以下函数实现相同的效果:
例如,Python中确定元素是否在列表中的递归搜索函数(谓词,因为它返回True
或False
)如下所示:
def search(lst, key):
if not lst: # base case: list is empty
return False
elif lst[0] == key: # base case: current element is searched element
return True
else: # recursive case: advance to next element in list
return search(lst[1:], key)
考虑到上述示例,很容易对其进行调整以解决原始问题—如何返回列表中元素的索引(如果找到)或False
(如果未找到):
酷。这就是递归发生的地方(正如您所指出的),通过调用函数本身,给定相同的
键
,但列表l
的子集(不包括第一个元素)
基本上,它会一直这样做,直到在列表中找到键。如果是,将返回True
。否则,将遍历整个列表,直到列表为空(所有元素都已检查是否与键
相等)。此时,算法放弃并返回False
这只会告诉您键是否在列表中,但不知道可以在何处找到索引。humm,代码似乎不会返回i,因此l[i]==key
哦,我明白了,所以它只是在元素上继续使用搜索,每次都会排除索引0?谢谢!我会对你的答案投赞成票,但我还没有足够的代表D:Edit:它适用于嵌套列表,但当我尝试使用此搜索时([1,[2,3],4,[5,[6,[],[8,9]],10]],8)
它没有返回任何东西?哦,而且我修改了我的代码,使它返回真的iff s存在于LTo中,添加到上面的注释中,经过一些测试后,它只适用于嵌套列表,如果嵌套列表是列表中的最后一个元素。我不知道为什么会发生这种情况D:@NickGong原始问题没有指定输入列表是嵌套的,这将导致一个完全不同的答案。此外,该函数将如何定义?例如,在一个列表中,如[1,2,3,4]
2的索引是什么?是1
?是0
?你必须将其作为不同的问题发布。好的,谢谢你的输入,我将发布不同的问题!
lst[0] # first element of a list
lst[1:] # rest of the elements in the list, after the first
def search(lst, key):
if not lst: # base case: list is empty
return False
elif lst[0] == key: # base case: current element is searched element
return True
else: # recursive case: advance to next element in list
return search(lst[1:], key)
def search(l, key):
if not l:
return False
elif l[0] == key:
return 0
else:
idx = search(l[1:], key)
return 1+idx if idx is not False else False