Home > Back-end >  Python: Using only recursion, make a pyramid pattern with an asterisk in between every time
Python: Using only recursion, make a pyramid pattern with an asterisk in between every time

Time:07-28

Rules: You can only use 1 argument, 1 print and 1 def while using recursion.

So it will look something like this:

def pattern(n):

    **Your code here**

There are 4 scenarioes.

pattern(0)

(No output)

pattern(1)

*

pattern(2)

*
**
*

patterns(3) will output

*
**
*
***
*
**
*

This is my code:

def stars(n, descending=True):
    if descending:
        print('*' * n)
        if n > 2:
            print('*', '\n', end='')

    if n == 1:
        if not descending:
            print('*')
        return

    stars(n - 1, descending)
    if not descending:
        print('*' * n)
        print('*', '\n', end='')


stars(5, descending=False)
stars(4)

How do I solve this question? I could do it but I used 2 arguments, 2 prints and it only works for 3 and above. Any help would be appreciated!

My answer (edit):

def pattern(n):
    if n > 0:
        pattern(n-1)
        print('*' * n)
        pattern(n-1)
    else:
        return


pattern(3)

This fits the question perfectly, but I assume there isn't a way to do pattern(4) and above?

CodePudding user response:

def pattern(n):
    if n > 0:
        pattern(n-1)
        print(n * "*")
        pattern(n-1)

The output is as you wish, for example

>>> pattern(3)
*
**
*
***
*
**
*

CodePudding user response:

def stars(n: int):
    num_range = list(range(1, n))
    num_range = num_range   num_range[0:-1][::-1]
    num_range = num_range   [n]   num_range
    for x in num_range:
        print("*" * x)

output

CodePudding user response:

"Recursion occurs when a thing is defined in terms of itself or of its type." (Wikipedia)
So, try to describe a pattern in terms of others, for example pattern(3) in terms of other patterns.

From the samples, one can see that pattern(3) is "pattern(2), then '*' 3 times, then pattern(2)" (and similarly with other samples other than n=0), but the pattern(0) is a special case to be handled.

def pattern(n):
    if n == 0: # base case 
        pass # this case does nothing
    else: # recursive case:
        pattern(n-1)
        print('*' * n)
        pattern(n-1)

It's also possible to simplify using if n > 0: without else, as MarianD's answer shows it. (I intentionally distinguish base case and recursive case here for illustration purposes, but it's not necessary in recursion)

Note that the demo will throw errors for invalid values:

  • n is negative number: RecursionError (base case never reached before it hits the limit)
  • n is non-integer positive number: In my demo, it keeps subtracting by 1 and the base case is never reached, too, so it ends up in RecursionError. But in any case, the string cannot be multiplied with n.
  • n is string: TypeError when trying n-1
    etc.

It's possible to modify the program to handle those cases (depending on what you want, here I just let it err).

One can use a loop to check print it from 0 to 5:

for n in range(6):
    print(f"n={n}:")
    pattern(n)
    print('')

output:

n=0:

n=1:
*

n=2:
*
**
*

n=3:
*
**
*
***
*
**
*

n=4:
*
**
*
***
*
**
*
****
*
**
*
***
*
**
*

n=5:
*
**
*
***
*
**
*
****
*
**
*
***
*
**
*
*****
*
**
*
***
*
**
*
****
*
**
*
***
*
**
*

Check if the patterns 4 and 5 are exactly what you want.

  • Related