Reputation: 1399
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
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
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
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