今天,数据结构课上,老师留了个匪夷所思的作业,就是用非递归的方法去实现谢尔平斯基三角形。
from turtle import *
def drawTriangle(points, color, myTurtle):
myTurtle.fillcolor(color)
myTurtle.up()
myTurtle.goto(points[0])
myTurtle.down()
myTurtle.begin_fill()
myTurtle.goto(points[1])
myTurtle.goto(points[2])
myTurtle.goto(points[0])
myTurtle.end_fill()
def getMid(p1, p2):
return( (p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2)
def sierpinski(points, degree, myTurtle):
colormap = ['#FFEBCD', '#00FFFF', '#B8860B', '#FF8C00', '#00BFFF', '#FF00FF', '#FFD700']
drawTriangle(points, colormap[degree], myTurtle)
if degree > 0:
# 递归方法
# sierpinski([points[0],
# getMid(points[0], points[1]),
# getMid(points[0], points[2])],
# degree-1, myTurtle)
# sierpinski([points[1],
# getMid(points[0], points[1]),
# getMid(points[1], points[2])],
# degree - 1, myTurtle)
# sierpinski([points[2],
# getMid(points[2], points[1]),
# getMid(points[0], points[2])],
# degree - 1, myTurtle)
n = 0
flag = 0
left = 0
for i in range(3):
sierpinski([points[n],
# 0 0 2 and 0 1 0
getMid(points[flag], points[1]),
getMid(points[left], points[2])],
degree-1, myTurtle)
n += 1
if n == 2:
flag = 2
else:
flag = 0
if n == 1:
left = 1
else:
left = 0
myTurtle = Turtle()
myWin = myTurtle.getscreen()
myPoints = [(-200, -100), (0, 200), (200, -100)]
sierpinski(myPoints, 4, myTurtle)
这里做了个笨方法完成了三层结构的谢尔平斯基三角形。