[1995 views]

Sierpinski triangle is also known as Sierpinski gasket and Sierpinski sieve. It is the object that is made after many iterations. It is basically a fractal and attractive fixed set. Its overall shape looks similar to an equilateral triangle.

Let's learn to draw Sierpinski triangle using python and turtle module. The first description of this triangle was given by a polish mathematician Waclaw Sierpinski in 1915. The shape is named after him. In this tutorial, you will learn about recursion, the Sierpinski triangle, and the turtle module.

Sierpinski triangle may look complex to you but it’s easy to make a shape with the help of repetition. You can use the recursive function and the turtle module of python to generate the Sierpinski triangle pattern. It’s the best and the simplest way of drawing it. However, the much easier way is by using your hands. Simply, start by drawing a large triangle on a paper. Now, it should be divided into four new triangles by joining the midpoint of each side. By applying the same process to the other three triangles at the corner, one can make a Sierpinski triangle.

Another way of drawing Sierpinski triangle in python is by using python tinkter. If you want to draw Sierpinski triangle, there are many ways to do it. This problem will be asked in interviews or an exam so you must practice it.

Recursion in programming refers to a function that calls itself. It is a way of solving a problem by dividing the problem into smaller problems and then finding the appropriate solution to it. A recursive algorithm is used to solve many problems. In recursion, programmers have to define a base case. It is used to stop the function from calling itself. If not defined, then the code will keep running. Recursion is quite helpful in programming. However, recursion can’t be used to solve every problem. We are going to use it for drawing Sierpinski triangle.

In the above code, the outer triangle will get drawn with the help of the sierpinski function. As you can see, three recursive calls exist in the code. One is for every new corner triangle that you will get after joining the midpoints. To understand the code, imagine that the corners have been ordered lower left, top, lower right.

The way the sierpinski function calls itself, it starts drawing from the smallest triangle in the lower-left corner. After that, it fills out the rest of the triangles going back. Now, the top corner will be filled starting from the smallest topmost triangle. In the end, it fills the lower right corner beginning from the smallest triangle. Sierpinski function depends on the getmid function. The begin_fill and end_fill turtle method draws a filled triangle.