Practice recursion

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):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import turtle


def single_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

def multiple_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)

def draw_art():

window=turtle.Screen()
window.bgcolor("white")

turtle0=turtle.Turtle()
turtle0.shape("arrow")
turtle0.color("red")
turtle0.pu()
turtle0.setpos(0,0)
turtle0.pd()

multiple_turtle_triangle(turtle0,2,200)
window.exitonclick()

draw_art()

Graph:

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import turtle

def draw_sierpinski(length,depth,some_turtle):
if depth==0:
for i in range(0,3):
some_turtle.fd(length)
some_turtle.left(120)
else:
draw_sierpinski(length/2,depth-1,some_turtle)
some_turtle.fd(length/2)
draw_sierpinski(length/2,depth-1,some_turtle)
some_turtle.bk(length/2)
some_turtle.left(60)
some_turtle.fd(length/2)
some_turtle.right(60)
draw_sierpinski(length/2,depth-1,some_turtle)
some_turtle.left(60)
some_turtle.bk(length/2)
some_turtle.right(60)

def draw_art():
window = turtle.Screen()
turtle0 = turtle.Turtle()
draw_sierpinski(100,3,some_turtle=turtle0)
window.exitonclick()

draw_art()

Graph: