Demons
Demons

Reputation: 179

Fractal drawing using recursion

I am working on an assignment in which you I have to create a fractal drawing using a given int, I am confused on how to use recursion here.

I am not asking for a full solution, rather maybe just something to get me started in the right direction. Here is what I have so far:

def fractal(length, spaces):

    if length == 1:
        print(' ' * int(spaces) + '*')
    else:
        print(fractal(length//2*'*',spaces*' '))
        print(fractal(spaces*' ',length*'*'))
        print(fractal(length//2*'*',spaces+(length//2)*' '))




while True:
    userlength = input('Enter an integer > 0:\n')
    try:
        userlength = int(userlen)
    except:
        continue
    if userlength < 0:
        continue
    else:
        fractal(userlength,userlength)
        break

Upvotes: 1

Views: 1401

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 177600

The best hint I can give is to implement each line of the description exactly as described.

For example, "Create a function def fractal(length,spaces)". You've done that:

def fractal(length,spaces):

"If length is 1 print out the number of spaces followed by 1 star. Note "print" and not "return".

    if length == 1:
        print(' ' * spaces + '*')

Etc... If you follow the description exactly, the code writes itself.

One thing that may not be clear from the description is that "print the fractal pattern" means "call the fractal function" with the parameters described. That's the actual recursion. The function has to call itself.

Upvotes: 2

Related Questions