我需要一些关于 python 程序的帮助。在我的 CPS II 类(class)中,我们学习了如何使用递归创建谢尔宾斯基三角形。我认为这很有趣,并在网上研究了更多主题。我一直在尝试编写代码来使用递归创建谢尔宾斯基地毯。我觉得我已经很接近了,但似乎无法完全理解。我完全不知道问题是什么。
在有人问之前,这不是家庭作业。我只是想通过示例练习更好地理解递归。
这是到目前为止我的代码;它只在深度 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()
最佳答案
x_1、x_2、y_1 和 y_2 的公式中必须同时包含 point[0] 和 point[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)
当然,你也有同样的想法。
关于python - Sierpinski 地毯递归 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9271682/