Pythonmatics

Solving mathematical problems with Python

Triangle surprise


My father used to program in the Logo language back in the 1980s. Although Logo also supported text-based commands, it was widely known for its use of turtle graphics. For those who are less familiar with this term, turtle graphics are based on a cursor (also known as a ‘turtle’) that the code can turn and move around to draw a graphical output. The Python programming language also has a vast turtle graphics library, and my father used to play with it a lot, remaking the creations he used to make with Logo.

One day, I came across a video on Facebook describing a surprising phenomenon. You start with an equilateral triangle and draw a point in a random location within it. Next, you randomly select one of the three vertices and draw a new point exactly in the middle between the original point and the selected vertex. You repeatedly continue in the same method: every time you randomly select one of the three vertices and draw a new point exactly in the middle between the previous point and the selected vertex. After some 30,000 points, an interesting shape starts to appear.

This called for a Python script using turtle graphics. I wrote the code and shared it with my father over WhatsApp. This was one month before he passed away. I admired my dad for his ability to pick up Python after turning 80 and his ability to get excited over the output of a short computer program.

It’s Python time

from turtle import *
from random import *

ht(); speed(0); pu(); seth(90)

color("red")
corners = []
for _ in range(3):
    fd(300); dot(5); corners.append(pos()); bk(300); rt(120)

color("blue")
currx,curry = corners[0]
for _ in range(30000):
    setpos(currx,curry); dot(3)
    x,y = choice(corners)
    currx,curry = (currx+x)/2,(curry+y)/2

done()

Output

Yes, surprisingly enough the output turns out to be the famous Sierpinski triangle – an equilateral triangle, subdivided recursively into smaller equilateral triangles.


Discover more from Pythonmatics

Subscribe now to keep reading and get access to the full archive.

Continue reading