Home > front end >  How to make a pyramid using recursion in python?
How to make a pyramid using recursion in python?

Time:10-27

I need to make a pyramid in python using recursion. Already made it, but I need help making it with recursion.

def pyramid(n):
    for i in range(0, n):

        for j in range(0, i 1):
    
            print("* ",end="")
      
        print("\r")
 
pyramid(5)

CodePudding user response:

Recursion = the repeated application of a recursive procedure.

Code:

def pyramid(n):
    if n==0:
        return
    else:
        pyramid(n-1)
        print("* "*n)

n = 10
pyramid(n)

This just repeats the function until n = 0.

CodePudding user response:

Matei's solution is reasonable, but since the original used a nested for loop instead of repeat, it's worth mentioning that both loops can be replaced by recursive calls:

def nstars(n):
    if n<=0:
        print('')
        return
    print('*',end='')
    nstars(n-1)

def pyramid(n):
    if n<=0:
        return
    pyramid(n-1)
    nstars(n)
  • Related