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.
My program works for the first case, but prints too many for the second case. The stipulations for this program are:
must be recursive
can only use the following turtle functions:
turtle.forward(100) <-- turtle goes forward 100 steps
turtle.right(90) <-- turtle turns right 90 degrees
turtle.penup() <-- turtle lifts its pen up off of the paper
turtle.forward(100) <-- turtle goes forward 100 steps
turtle.pendown() <-- turtle puts its pen down on the paper
turtle.pencolor("red") <-- turtle uses red pen
turtle.circle(100) <-- turtle draws circle of radius 100
turtle.pencolor("blue") <-- turtle changes to blue pen (most other common colors work too!)
turtle.forward(50) <-- turtle moves forward 50 steps
turtle.xcor() <-- turtle returns its current x-coordinate
turtle.ycor() <-- turtle returns its current y-coordinate
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
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,.