Matthew Hanson
Matthew Hanson

Reputation: 331

Triangle of Stars using recursion Python

So I have an assignment to write some simple functions recursively. One of them is to make a triangle of stars based on an inputted height. for example:

stars(5)

will print out:

*
**
***
****
*****

and this function works just fine in doing that.

def stars(height):
    x = 1
    while x <= height:
        print ('*' * x)
        x += 1

How can I write this recursively? Any help is greatly appreciated.

Upvotes: 0

Views: 13235

Answers (5)

vikramls
vikramls

Reputation: 1822

How about this one to print in both ascending and descending form?

def stars(n, descending=True):
    if (descending):
        print '*'*n

    if n==1:
        if not descending:
            print '*'
        return

    stars(n-1, descending)
    if not descending:
        print '*'*n

stars(5)
print
stars(5, descending=False)

Output:

*****
****
***
**
*

*
**
***
****
*****

Upvotes: 2

Tanveer Alam
Tanveer Alam

Reputation: 5275

This is one of the way to call it recursively.

def stars(height, sub=0):
    if sub < height:
        print "*"*(height-(height-1)+sub)
        stars(height, sub+1)

stars(5)

Results:

*
**
***
****
*****

Upvotes: 0

victor175
victor175

Reputation: 624

Initially call it with the desired height and 0 for the number of stars.

 def stars(height, x):
        if x < height:
           return
        else:
           print ('*' * x)
           stars(height, x + 1)

Upvotes: 0

Malik Brahimi
Malik Brahimi

Reputation: 16711

That's easy, just add one until the height is reached. Use a default value and call star(12).

def star(h, n = 1):
    if h == n:
        print n * '*'

    if h != n:
        print n * '*'
        star(h, n + 1)

Upvotes: 0

aldeb
aldeb

Reputation: 6838

I would go for this:

def recurse_triangle(num, char):
    if num > 0:
        recurse_triangle(num-1, char)
        print(char*num)

recurse_triangle(5, '*')

Output:

*
**
***
****
*****

Upvotes: 3

Related Questions