Sierpinski地毯递归 - Python

时间:2012-02-14 04:24:06

标签: python recursion

我需要一些python程序的帮助。在我的CPS II课程中,我们讨论了如何使用递归创建sierpinski三角形。我认为这非常有趣,并在线查看更多主题。我一直试图用代码来创建使用递归的sierpinski地毯。我觉得我很亲密,但似乎无法一路走好。我完全不知道问题是什么。

在有人问之前,这不是功课。我只是通过实例练习来更好地理解递归。

到目前为止,这是我的代码;它只适用于深度1.然后在深度2它有点工作,但有些事情是错误的。

from graphics import *
import sys

def sierpinskiCarpet(points, level, window):

    if level == 0:
        square = Rectangle(points[0], points[1])
        square.draw(window)
    else:
        x_0 = (points[0].getX())
        x_02 = (points[1].getX())
        x_1 = ((points[1].getX())/3)
        x_2 = (((points[1].getX())/3)*2)

        y_0 = (points[0].getY())
        y_02 = (points[1].getY())
        y_1 = ((points[0].getY())/3)
        y_2 = (((points[0].getY())/3)*2)


        top1 = [points[0], Point(x_1, y_2)]
        top2 = [Point(x_1, y_0), Point(x_2, y_2)]
        top3 = [Point(x_2, y_0), Point(x_02, y_2)]

        med1 = [Point(x_0, y_2), Point(x_1, y_1)]
        med3 = [Point(x_2, y_2), Point(x_02, y_1)]

        bottom1 = [Point(x_0, y_1), Point(x_1, y_02)]
        bottom2 = [Point(x_1, y_1), Point(x_2, y_02)]
        bottom3 = [Point(x_2, y_1), points[1]]


        sierpinskiCarpet(top1, level - 1, window)
        sierpinskiCarpet(top2, level - 1, window)
        sierpinskiCarpet(top3, level - 1, window)
        sierpinskiCarpet(med1, level - 1, window)
        sierpinskiCarpet(med3, level - 1, window)
        sierpinskiCarpet(bottom1, level - 1, window)
        sierpinskiCarpet(bottom2, level - 1, window)
        sierpinskiCarpet(bottom3, level - 1, window)


def main():
    #get the depth from the system arguemtns
    depth = int(sys.argv[1])
    #set up the window using GraphWin
    window = GraphWin('Sierpinski Carpet', 500, 500)
    #set the corrdiantes of the window
    window.setCoords(-0.1, -0.1, 1.1, 1.1)
    #list the starting points for the first square
    points = [Point(0, 1), Point(1, 0)]

    #call the function with the points
    sierpinskiCarpet(points, depth, window)
    #close the window when clicked
    window.getMouse()

main()

1 个答案:

答案 0 :(得分:2)

x_1,x_2,y_1和y_2必须在公式中包含点[0]和点[1]部分。

x_0 = (points[0].getX())
x_02 = (points[1].getX())
x_1 = (((points[0].getX())/3)*2 +  (points[1].getX())/3)
x_2 = (((points[0].getX())/3)   + ((points[1].getX())/3)*2)

当然,同样的想法来自y。