3
I’m having trouble solving an exercise. The statement is as follows: Implement the annoy(n) function that returns a string containing "annoy " (the word followed by a space) n times. If n is not a strictly positive integer, the function must return an empty string. This function must be implemented using recursion.
Using the above function, implement the elephants(n) function that returns a string containing the letter "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 callback elephants(4) must 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’ve only succeeded 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
Have to [Edit] the question and add your codes?
– Woss
Only get to implement the first function. I will put.
– Rafael Lima