Reputation: 135
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.
Upvotes: 2
Views: 808
Reputation: 8711
The following does what you appear to want.
def repeat(n):
def stars(n):
return '*'+stars(n-1)+'!' if n > 0 else ''
print stars(n)
For example, repeat(5)
prints *****!!!!!
and repeat(8)
prints
********!!!!!!!!
.
Upvotes: 1
Reputation: 251116
I would use two strings here, and return a concatenated string of those two strings when n<=0
and use return
instead of printing inside function:
def repeat(n, strs1="", strs2=""): # The Default value of strings is ""
if n <= 0:
return strs1 + strs2 # if n<=0 then concatenate the two strings and return them
else:
strs1 += "*" # Add * to strs1
strs2 += "!" # Add ! to strs2
return repeat(n-1, strs1, strs2) # Pass n-1, as well as the two strings to a recursive call
print(repeat(5))
print(repeat(3))
Output:
*****!!!!!
***!!!
Upvotes: 0
Reputation: 430
I don't actually know what you're asking... If there's a more efficient or better way of doing this? This would be quite obvious:
def repeat(n):
if n >= 0:
print((n*'*')+(n*'!'), end=' ')
return repeat(n-1)
Upvotes: 0
Reputation: 236124
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)
> *****!!!!!
Upvotes: 3
Reputation: 4723
Assume you have a solution for n - 1
. Prepend *
and append !
.
def repeat(n):
if n > 0:
print("*", end=" ")
repeat(n - 1)
print("!", end=" ")
Upvotes: 1