im trying to return all the middle letters in a string, eg, list = ["Guesss", "what", "idk"]
which would return ead
where if list[i]
is odd it gets the middle letter and if list[i]
is even it gets the second middle letter like in what
the middle letters are ha
and returns the second letter a
.
How can I do this using recursion? - with no loops
This is what I've come up so far:
def get_middle_letters(words):
if words == []:
return ""
if len(words[0]) % 2 == 1:
middle = len(words[0]) // 2
return (words[0][middle]) (get_middle_letters(words[1:]))
elif len(words[0]) % 2 == 0:
middle = len(words[0]) // 2
return ((words[0][middle 1]) (get_middle_letters(words[1:])))
words = ['Humans', 'are', 'lazy']
print(get_middle_letters(words))
print(get_middle_letters([]), "#EMPTY")
print(get_middle_letters(['words']))
CodePudding user response:
def middle_letters(words):
if len(words) == 0:
return ""
else:
return words[0][len(words[0])//2] middle_letters(words[1:])
print(middle_letters(["Guesss", "what", "idk"])) # sad
The answer should be 'sad' according to your logic.
CodePudding user response:
'lazy'
has four characters, so the middle == 2
.
'lazy'[2 1] == 'y'
, but you wanted z
, which is at index 2.
You don't need the 1
.
That being said, you don't need to check even/odd at all. Your odd length strings already work.
CodePudding user response:
A possible recursive approach:
def middle_letters(words: list):
# base case
if not words:
return ''
# recursive case
last = words.pop()
return middle_letters(words) last[len(last) // 2]
Behold, the power of a one-liner:
def middle_letters(words: list):
return (middle_letters(words[:-1]) words[-1][len(words[-1]) // 2]) if words else ''
Test
print(repr(middle_letters([])))
print(repr(middle_letters(['Humans', 'are', 'lazy'])))
print(repr(middle_letters(["Guesss", "what", "idk"])))
Out[1]:
''
'arz'
'sad'