If a letter (string) is in a list, find_letter(['o', ['hello', 'c', 'bye']), return True, if not return 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))
It does return 'True', but I am not sure if this is the right way to do this. Maybe there's a better way? In the second elif-statement, is python going through all the elements in the list if the first one doesn't contain the letter? The function must be recursive.
I think the most pythonic approach would be to use
def find_letter(letter, lst):
return any(letter in word for word in lst)
The beauty of this is that it iterates over lst
and returns as soon as one of the words in that list contains letter
. Also, it doesn't need to recurse.
This returns False
instead of 0
if lst
is empty, though (unlike your program) but since False
evaluates to 0
anyway (and vice versa), that's not really an issue.
Since you need a recursive version:
Short version
def find_letter(let, lst):
return (lst or False) and \
((isinstance(lst[0], str) and let in lst[0]) or find_letter(let, lst[1:]))
More explicit version
def find_letter(let, lst):
if lst:
e = lst[0]
return (isinstance(e, str) and let in e) or find_letter(let, lst[1:])
return False
Even more explicit version
def find_letter(let, lst):
if lst:
e = lst[0]
if isinstance(e, str) and let in e:
return True
return find_letter(let, lst[1:])
return False
Note that I leave out a couple of else:
because they are not necessary after a return
statement. If you don't want to test for a letter in a string, but just for equality, replace let in ...
by let == ...
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With