user1681664
user1681664

Reputation: 1811

Python Turtle Recursion Tree

I am suppose to write a program using python's turtle that creates a tree with levels. Below are some I/O's so you see what it is suppose to do.

enter image description here

My program works for the first case, but prints too many for the second case. The stipulations for this program are:

My Program:

import turtle

def tree(length,n):
    """ paints a branch of a tree with 2 smaller branches, like an Y"""
    if length < (length/n):
           return       # escape the function
    turtle.forward(length)        # paint the thik branch of the tree
    turtle.left(45)          # rotate left for smaller "fork" branch
    tree(length * 0.5,length/n)      # create a smaller branch with 1/2 the lenght of the parent branch
    turtle.right(90)         # rotoate right for smaller "fork" branch
    tree(length * 0.5,length/n)      # create second smaller branch
    turtle.left(45)          # rotate back to original heading
    turtle.backward(length)       # move back to original position
    return              # leave the function, continue with calling program

Upvotes: 3

Views: 18734

Answers (1)

Jeremiah
Jeremiah

Reputation: 1456

I think there are two problems.

First, for the recursive calls, the second parameter should be n-1 instead of length/n. If you're drawing level n, the next call will draw level n-1, not level length/n.

The second problem is the escape condition. With the first change, the drawing will finish when there are no more levels left to draw, or n==1.

It sounds like homework, so I won't post the exact code,.

Upvotes: 7

Related Questions