I am trying to create the Sierpinski carpet in python using turtle. This is my code so far:
from turtle import *
# Make a screen and a pen
pen = Pen()
screen = Screen()
pen.speed(0)
pen.color('orange')
pen.width(1.5)
def s (n, l):
for i in range (4):
s(n-1, l)
pen.right(45); pen.forward(l); pen.right(45)
s(n-1, l)
pen.left(90); forward (l); pen.left(90)
s(n-1, l)
pen.right(45); pen.forward(l); pen.left(45)
s(n-1, l)
However whenever I run it I get this message:
line 17, in s
s(n-1, l)
[Previous line repeated 990 more times]
RecursionError: maximum recursion depth exceeded
I tried using if i in range(4):
but this does not work either, where am I going wrong?
You need "stop condition" to stop recursion.
For example:
if n == 0: # "stop condition"
# draw or exit
else: # recursions
# execute some recursions
I don't know algorithm but I created carpet with this code.
I use trace(0)
and update()
only to draw it much faster.
#!/usr/bin/env python3
import turtle
# --- functions ---
def s(n, l):
if n == 0: # stop conditions
# draw filled rectangle
turtle.color('black')
turtle.begin_fill()
for _ in range (4):
turtle.forward(l)
turtle.left(90)
turtle.end_fill()
else: # recursion
# around center point create 8 smalles rectangles.
# create two rectangles on every side
# so you have to repeat it four times
for _ in range(4):
# first rectangle
s(n-1, l/3)
turtle.forward(l/3)
# second rectangle
s(n-1, l/3)
turtle.forward(l/3)
# go to next corner
turtle.forward(l/3)
turtle.left(90)
# update screen
turtle.update()
# --- main ---
# stop updating screen (to make it faster)
turtle.tracer(0)
# start
s(4, 400)
# event loop
turtle.done()
Wikipedia: Sierpinski carpet
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments