Jason Schayer
Jason Schayer

Reputation: 171

print pattern recursion

I need to write a recursive function printPattern() that takes an integer n as a parameter and prints n star marks followed by n exclamation marks, all on one line. The function should not have any loops and should not use multiplication of strings. The printing of the characters should be done recursively only. The following are some examples of the behavior of the function:

>>>printPattern(3)
***!!!
>>>printPattern(10)
**********!!!!!!!!!!

This is what I have at the moment

def printPattern(n):
if n < 1:
    pass
else:
    return '*'*printPattern(n)+'!'*printPattern(n)

I know I am completely off, and this would be easier without recursion, but it is necessary for my assignment.

Upvotes: 2

Views: 11482

Answers (3)

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236124

Try this:

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

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

Upvotes: 2

nneonneo
nneonneo

Reputation: 179602

Q: What's printPattern(0)?
A: Nothing.

Q: What's printPattern(n), for n>=1?
A: *, then printPattern(n-1), then !.

Now you should be able to do it. Just remember to think recursively.

Upvotes: 3

Amber
Amber

Reputation: 527213

Recursion is based on two things:

  • a base case
  • a way to get an answer based off something closer to the base case, given something that's not the base case.

In your case, the simplest base case is probably 0 - which would print thing (the empty string). So printPattern(0) is ''.

So how do you get closer to 0 from your input? Well, probably by reducing it by 1.

So let's say that you are currently at n=5 and want to base your answer off something closer to the base case - you'd want to get the answer for n=5 from the one for n=4.

The output for n=5 is *****!!!!!.

The output for n=4 is ****!!!!.

How do you get from the output of n=4 to n=5? Well, you add a * on the front and a ! on the end.

So you could say that printPattern(5) is actually just '*' + printPattern(4) + '!'.

See where this is going?

Upvotes: 2

Related Questions