谢尔宾斯基三角形(英语:Sierpinski triangle)是一种分形,由波兰数学家谢尔宾斯基在1915年提出
取一个实心的三角形。(多数使用等边三角形)沿三边中点的连线,将它分成四个小三角形。去掉中间的那一个小三角形。对其余三个小三角形重复1。取一个正方形或其他形状开始,用类似的方法构作,形状也会和谢尔宾斯基三角形相近。

import turtle
def drawTriang(points,color,Turtle):Turtle.fillcolor(color)Turtle.up()Turtle.goto(points[0][0],points[0][1])Turtle.down()Turtle.begin_fill()# 位置归一Turtle.goto(points[1][0],points[1][1])Turtle.goto(points[2][0],points[2][1])Turtle.goto(points[0][0],points[0][1])Turtle.end_fill()
代码如下:
def getMids(p1,p2):
return ((p1[0]+p2[0])/2,(p1[1]+p2[1])/2)
def sierpinski(points,degree,myTurtle):colormap=['pink','red','green','yellow','violet','orange']drawTriang(points,colormap[degree],myTurtle)if degree>0:sierpinski([points[0],getMids(points[0],points[1]),getMids(points[0],points[2])],degree-1,myTurtle)sierpinski([points[1],getMids(points[0],points[1]),getMids(points[1],points[2])],degree-1,myTurtle)sierpinski([points[2],getMids(points[2],points[1]),getMids(points[0],points[2])],degree-1,myTurtle)
def main():Turtle=turtle.Turtle()myWin=turtle.Screen()Points=[[-200,-100],[0,200],[200,-100]]sierpinski(Points,3,Turtle)myWin.exitonclick()if __name__=="__main__":main()