Reputation: 21
I do need to create two recursive functions in Python. the first function should create a pyramid with a given parameter n
. for example pyramid(3)
should have the following output
*
***
*****
I came up with the following function:
def pyramid(n, i=0):
if n == 0:
return 0
else:
print(" "*(n-1) +"*"*(2*i+1)+ " "*(n-1))
return pyramid(n-1, i+1)
Now I do need to create a second recursive function pyramid_seq
with 2 parameters n,k
what prints a sequence of pyramids in with height of n
. for example pyramid_seq(3,4)
should have the following output:
* * * *
*** *** *** ***
********************
Upvotes: 2
Views: 2033
Reputation: 42133
If you want to properly leverage the power of recursion, your function should return their result as data and the printing part should be separate. This will allow you to reuse a previously defined function to produces new results from it:
def pyramid(h):
if h==1: return ["*"]
return [" "+p+" " for p in pyramid(h-1)]+["*"*(2*h-1)]
The function returns an array of lines (strings) that you can print or reuse for something else:
print(*pyramid(5),sep="\n")
*
***
*****
*******
*********
Because you now have a function that generates a pyramid as a list of lines, you can reuse it to concatenate its result to form a series of pyramids without reinventing the wheel:
def pyramids(h,w):
return [p*w for p in pyramid(h)]
print(*pyramids(4,6),sep="\n")
* * * * * *
*** *** *** *** *** ***
***** ***** ***** ***** ***** *****
******************************************
If your second function also needs to be recursive, you can still reuse the first one to build it:
def pyramids(h,w):
if w == 1: return pyramid(h)
return [ ps+p for ps,p in zip(pyramids(h,w-1),pyramid(h)) ]
Upvotes: 1
Reputation: 504
Add another parameter to your function (notice the changes in the recursive call) that determines how many times you should print every line. This will create the desired effect.
def pyramid(n, k, i=0):
if n == 0:
return 0
else:
print(k*(" "*(n-1) +"*"*(2*i+1)+ " "*(n-1)))
return pyramid(n-1, k, i+1)
Output for pyramid(4, 6)
:
* * * * * *
*** *** *** *** *** ***
***** ***** ***** ***** ***** *****
******************************************
Upvotes: 2