I can not solve an exercise. The statement is as follows: Implement the uncomfortable (n) function that returns a string containing "bother" (the word followed by a space) n times. If n is not a strictly positive integer, the function should return an empty string. This function should be implemented using recursion.
Using the above function, implement the elephants (n) function that returns a string containing the letter of "An elephant bothers a lot of people ..." from 1 to n elephants. If n is not greater than 1, the function should return an empty string. This function should also be implemented using recursion.
For example, the return of the elephants (4) call should be:
Um elefante incomoda muita gente
2 elefantes incomodam incomodam muito mais
2 elefantes incomodam incomodam muita gente
3 elefantes incomodam incomodam incomodam muito mais
3 elefantes incomodam incomodam incomodam muita gente
4 elefantes incomodam incomodam incomodam incomodam muito mais
How can I implement the second function recursively? So far I have only managed it as an iterative function.
def incomodam(n):
if n <= 0:
return ''
else:
return 'incomodam ' + incomodam(n - 1)
def elefantes(n):
if n <= 1:
return ''
else:
count = 1
string = 'Um elefante incomoda muita gente '
while count < n:
count += 1
if count < n:
string += str(count) + ' elefantes ' + incomodam(count) + 'muito mais '
string += str(count) + ' elefantes ' + incomodam(count) + 'muita gente '
else:
string += str(count) + ' elefantes ' + incomodam(count) + 'muito mais '
return string