23k
23k

Reputation: 1399

Recursively printing a pyramid pattern with custom spacing

I'm successfully printing a recursive pyramid pattern in python, but I want to be able to add custom spacing, and I'm running into errors with the attempts that I've made.

Here is the code I have:

def printstack(n, indent = 0):
    if n == 0:
        return 'U'
    else:
        print(' '*(n-1) + 'U '*(indent+1))
        printstack(n-1, indent+1)

Example:

>>> printstack(3)
   U
  U U
 U U U

>>> printstack(3,1)
  U U 
 U U U 
U U U U

Expected Results

>>> printstack(3,1)
    U
   U U
  U U U

Upvotes: 2

Views: 2205

Answers (3)

AlokThakur
AlokThakur

Reputation: 3751

Check below code, I think you are looking something like this-

>>> def printstack(n, indent=0):
...     if n > 0:
...         printstack(n-1, indent+1)
...         print(' '*indent + 'U '*n)


>>> printstack(3)
  U 
 U U 
U U U 
>>> printstack(3,1)
   U 
  U U 
 U U U 
>>> printstack(3,2)
    U 
   U U 
  U U U 

Upvotes: 2

pjs
pjs

Reputation: 19855

This seems to produce what you say you want, and is a bit simpler as well. Note that the extraneous return has been removed.

def printstack(n, indent = 0):
    if n > 0:
        printstack(n-1, indent+1)
        print(' ' * indent + 'U ' * n)

Upvotes: 3

roadrunner66
roadrunner66

Reputation: 7941

def printstack(n, indent = 0,spaces=3):
    if n!=0:
        printstack(n-1, indent+1+spaces/2,spaces )
        print(' '*indent + ('U'+' '*spaces)*n )

printstack(5,6,1)

output:

      U 
     U U 
    U U U 
   U U U U 
  U U U U U 

changing spaces:

printstack(5,6,3)

output

          U   
        U   U   
      U   U   U   
    U   U   U   U   
  U   U   U   U   U   

Upvotes: 1

Related Questions