2
我需要一些幫助Python程序。在我的CPS II課程中,我們回顧瞭如何使用遞歸創建sierpinski三角形。我認爲這很有趣,並在網上尋找更多的話題。我一直在想出使用遞歸創建sierpinski地毯的代碼。我覺得我很接近,但似乎無法完成。我完全不知道問題是什麼。謝爾賓斯基地毯遞歸 - Python的
而且有人問過,這不是功課。我只是試圖通過實例來更好地理解遞歸。
這裏是我到目前爲止的代碼;它只能在深度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()
這是正確的。但是我發現了另一個錯誤。 y值平方點分配也需要改變。 top3 = [Point(x_2,y_0),Point(x_02,y_0),Point(x_2,y_1)] top3 = [Point(x_2,y_0) Y_1)] 和 bottom1 = [點(X_0,Y_2),點(X_1,y_02)] bottom2 = [點(X_1,Y_2),點(X_2,y_02)] bottom3 = [點(X_2 ,y_2),points [1]] 這是正確的。感謝您的幫助! – tknickman 2012-02-14 17:32:20