user1550365
user1550365

Reputation: 11

Recursively print diamond in python

Can anyone help me out here, I am stuck on the base cases for turning this code into a recursive function... Can't use loops in the recursive function obviously.

def diamond(a):

assert a > 0, "width must be greater than zero"


for i in range(0, a, 2):

    for c in range(0, a - i, 2):
        print(" ", end='')

    if a % 2 == 0:
        i += 1

    for m in range(0, i - 1):
        print("*", end='')

    print()


for i in range (0, a, 2):

    for c in range(0, i, 2):
        print(" ", end='')

    for m in range(0, a - i):
        print("*", end='')

    print()

Upvotes: 1

Views: 3155

Answers (2)

Scarlet McLearn
Scarlet McLearn

Reputation: 71

Try this

def triangles(n):
     if not n & 1:
         raise ValueError('n must be odd')
    print_diamond(0, n, n >> 1)

def print_diamond(start, stop, midpoint):
    if start < stop:
        if start <= midpoint:
            print('  ' * (midpoint - start) + '* ' * ((start << 1) + 1))
        else:
            print('  ' * (start - midpoint) + '* ' * ((stop - start << 1) - 1))
        print_diamond(start + 1, stop, midpoint)

triangles(5)

Upvotes: 0

Lennart Regebro
Lennart Regebro

Reputation: 172309

Because this must be homework, I won't give you the code, but explain how to do it in words:

Instead of looping, you make a function that calls itself, and passes the variables you need as parameters. Then you have a test with an "if" in the function that when true, stops the looping and instead returns. That was you will then "fall" out of the loop.

So in this case you would pass in a and i as parameters, increase i with one in the function, and when i is greater than a, just return.

Upvotes: 1

Related Questions