hello,
I was wondering if I could recieve some help?
The function I am writing is called pyramid, it consumes a number and produces stars(*) from 1 to that number. For example pyramid(5) would be:
*
**
***
****
*****
so far I have a function that does that backwards and it's

def leftTriangle(n):
    """
    consumes: a number
    produces: that amount of stars all the way down to 1
    """
    """
    >>> leftTriangle(4)
    ****
    ***
    **
    *
    """
    if n == 0:
        return
    if n> 0:
    print n * ('*')
    leftTriangle(n-1)

and the code so far for the pyramid function that I am trying to create is

def pyramid(n):
    if n==0:
        print 
    if n>0:
        print ((((n-n)+1)* ('*'))

I am not sure what I could add in there where it could go up from 1 star to the number given. Any help?

Nifty use of recursion!

If you *don't* need to have a recursive function, then you could simply use a 'for' loop:

def triangle(n):
    for i in range(1,n+1):
       print '*' * i

Working backwards, we remember the basic rule: anything doable with iteration can be done with recursion, and vice-versa. So how can we turn our loop into a recursive function?

Note that in your leftTriangle function, you print the '*'s and then call leftTriangle(n-1). The result is 5 stars, followed by 4 stars, etc. What if we reversed the function call and the print?

def rightTriangle(n):
   if n == 0:
      return
   elif n > 0:
      rightTriangle(n-1)
      print '*' * n

Voila!

Hope it helps,
Jeff

Thank you so much Jeff, I am kind of kicking myself for it now haha can't believe I tried all these different ways to make it work and all I needed to do was flip it. Thank you once again for all the help.

This article has been dead for over six months. Start a new discussion instead.