Draw sierpinski triangle using turtle in python. If one tries to draw the biggest triangle first, he/she will find the method has very bad extensibility since there will be too many position. The first version (it’s not good at all and I know it):
defsingle_turtle_triangle(some_turtle,length): position=[] for i in range(0,3): some_turtle.forward(length) position.append(some_turtle.pos()) some_turtle.left(120) some_turtle.forward(length/2) position.append(some_turtle.pos()) some_turtle.left(120) for i in range(0,3): some_turtle.forward(length/2) position.append(some_turtle.pos()) some_turtle.right(120) some_turtle.setheading(0) some_turtle.up() del position[-1] return position
defmultiple_turtle_triangle(some_turtle,recursion,length): position = single_turtle_triangle(some_turtle,length) turtles=[] n=recursion S=n*(n+1)*(n+2)/6-(n-1)*(n)*(n+1)/6 for i in range(0,S): turtles.append(some_turtle) i=2 for i_turtle in turtles: i_turtle.pu() i_turtle.setpos(position[i]) i_turtle.pd() single_turtle_triangle(i_turtle,length/2) i=i+1 print(position)
Actually there is a traditional way to draw recursion shape like this. See koch fractals. Inspired by this, a good version of Sierpinski triangle should look like this: