Example sierpinski.py

This image is a Siepinski triangle, a famous fractal image. It is drawn recursively.

Code

import sympl.tkcanvas
 
length = 500
p1 = (0, length)
p2 = (length, length)
p3 = (length/2, length*(1-0.8660))
triangles = []
 
# Find midpoint of points a(x y) and b(x, y)
def midpoint(a, b):
    return((a[0]+b[0])/2, (a[1]+b[1])/2)
 
def sierpinski(level, p1, p2, p3):
    level -= 1
    if level:
        q1 = midpoint(p1, p2)
        q2 = midpoint(p2, p3)
        q3 = midpoint(p3, p1)
        sierpinski(level, p1, q1, q3)
        sierpinski(level, q1, p2, q2)
        sierpinski(level, q3, q2, p3)
    else:
        triangles.append([p1, p2, p3])
 
 
def draw(canvas):
    sierpinski(10, p1, p2, p3)
    for t in triangles:
        canvas.create_line(t[0], t[1], fill='green', width=1)
        canvas.create_line(t[1], t[2], fill='green', width=1)
        canvas.create_line(t[2], t[0], fill='green', width=1)
 
sympl.tkcanvas.tk_image(length, length, draw)

The sierpinski function takes a triangle (p1, p2, p3). It defines 3 more points (q1, q2, q3) which are the mid points between the original points. This creates 4 triangles, A, B, C , D. The function is called once more to create smaller triangles out of A, B and C. Triangle D is left empty.

A true Sierpinski triangle repeats this process forever, creating smaller and smaller triangles. Our code only recurses a few times decrementing level each time. When the value reaches zero, we append the current triangle to the list.

When all the triangles have been calculated, the draw function draws them all. For a 500 pixel image, there is no point setting a depth of greater than 9, because the triangles become too small to plot.