ras*_*eme 4 python string recursion list
如果一个字母(字符串)在列表中,find_letter(['o',['hello','c','bye']),则返回True,如果不返回False.
def find_letter(lst):
lst=['o','hello', 1]
n='o'
if not lst:
return 0
elif lst[0] == n:
return True
elif find_letter(lst[0:]):
return True
else:
return False
print(find_letter(lst))
Run Code Online (Sandbox Code Playgroud)
它确实返回'True',但我不确定这是否是正确的方法.也许有更好的方法?在第二个elif语句中,如果第一个元素不包含字母,python是否会遍历列表中的所有元素?该函数必须是递归的.
Tim*_*ker 15
我认为最pythonic的方法是使用
def find_letter(letter, lst):
return any(letter in word for word in lst)
Run Code Online (Sandbox Code Playgroud)
这样做的好处在于它迭代lst并在该列表中的一个单词包含后立即返回letter.此外,它不需要递归.
然而,这返回False而不是0if lst是空的(与你的程序不同),但由于无论如何False评估0(反之亦然),这不是一个真正的问题.
这是你的错误
def find_letter(lst): # You receive your list as lst
lst=['o','hello', 1] # Opppsss! You override it. It does not matter what you receive with lst above, now its value is ['o','hello', 1]
n='o'
Run Code Online (Sandbox Code Playgroud)
因此find_letter(lst[0:]),在 中,您使用列表切片,但lst=['o','hello', 1]在线时,您再次覆盖它,并且始终在列表的第一个元素上执行搜索。
n = "o" # you can set this too, but this is optional
def find_letter(lst):
# do not set a value to lst in here
if not lst:
return 0
elif lst[0] == n: # You checked first element in here
return True
elif find_letter(lst[1:]): # since you checked the first element, skip it and return the orher elements of the list
return True
else:
return False
lst = ['o','hello', 1]
print find_letter(lst)
Run Code Online (Sandbox Code Playgroud)