Friday, November 13, 2009

Recursive Koch curves in python


I have an ongoing project to teach programming to children. I recently discovered the python turtle module, so I'm learning python. So far it is an order of magnitude easier to deal with than Squeak or Berkeley Logo.

I was able to do simple rotating iterated shapes while still getting used to the python syntax. After maybe three hours total of learning, I was also able to implement my first recursive fractal, the Koch Snowflake.

def kochline(forward,num=1):
 if num == 0:
  turtle.forward(forward)
 else:
  newforward=forward/3
  newnum=num-1
  kochline(newforward,newnum)
  turtle.left(60)
  kochline(newforward,newnum)
  turtle.right(120)
  kochline(newforward,newnum)
  turtle.left(60)
  kochline(newforward,newnum)
 return

def kflake(size=100,depth=2):
 for i in range(0,3):
  kochline(size,depth)
  turtle.right(120)
 return

The function kochline recursively draws a line to the requested depth, this has a depth of 5 or 6:



kflake just calls kochline 3 times and rotates appropriately.

No comments:

Post a Comment