jwl4 jwl4 - 2 months ago 8
Python Question

Python beginner recursion

I am trying to get a simple function which takes n and prints

If n > 0:
print((n*'*')+(n*'!'), end=' ')


and trying to get the same solution but recursively. I am a beginner to recursion, and often I get the "higher level of thinking", but I am having trouble understanding the code that must follow.

My base case is that when n is 0 it prints nothing. When n is more than 1 it will print n copies of * + n copies of!

def repeat(n):
if n <= 0:
pass
else:
repeat(n-1)
print((n*'*')+(n*'!'), end=' ')


right now it prints n, and then n-1 successively until 0. I have tried breaking it up into two print statements and using more than one recursion .. but it becomes a messy pattern.

I am also not allowed to use loops. This one is driving me insane; I have come up with several solutions to it besides the easy one line statement, but none that use recursion.

Answer

It's simpler if you build and return a string and print it outside of the function, like this:

def printPattern(n):
    if n <= 0:
        return ''
    return '*' + printPattern(n-1) + '!'

Or as a one-liner:

def printPattern(n):
    return '*' + printPattern(n-1) + '!' if n > 0 else ''

Either way, this works:

print printPattern(5)
> *****!!!!!
Comments