我正在尝试制作一个 python 程序(仅使用递归,不使用循环),它从用户那里获取一个名称列表以及一个用于搜索该列表的名称。该程序必须判断该名称是否存在于给定列表中。此外,如果列表中的一个元素是 "James Christ"
并且我们搜索 "James"
,程序应该返回 true。
我已经做了一半的程序。但是我的代码没有执行附加功能。
我的代码是这样的:
L1=list(input("Enter the list of names : "))
x=input("Enter the name to search : ")
def search(L1,x):
if len(L1)==0:
return "Not found!!"
else:
if x==L1.pop(0):
return "Entry found!!"
else:
return search(L1,x)
print search(L1,x)
请帮帮我!
最佳答案
这是一种不破坏原始列表的解决方案。
montys = [
'John Cleese', 'Graham Chapman', 'Terry Gilliam',
'Eric Idle', 'Terry Jones', 'Michael Palin']
actor = 'Idle'
def search(data, word):
if len(data) == 0:
return "Not found!"
else:
if word in data[0]:
return "Entry found!"
else:
return search(data[1:], word)
print(search(montys, actor))
有关更多信息,请参阅 Junuxx 答案。
关于python - 如何仅使用递归在 python 中制作列表搜索程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15067891/