递归问题... Sierpinskis三角形

时间:2019-03-31 17:37:38

标签: python recursion

我正在研究sierpinskis三角形,但由于出现此错误,似乎无法超越前两个迭代:

8.py", line 43, in drawTriangle
    t.setposition(x,y)
AttributeError: 'float' object has no attribute 'setposition'

为什么它的浮点数是“ t”?

下面是我们到目前为止的代码...

def drawFractal(t, order, size):
    """The base case is just a rightside-up triangle"""                  
    t.forward(size)   
    t.left(120)                 
    t.forward(size)  
    t.left(120)               
    t.forward(size)    
    t.left(120)
    (x, y) = t.position()
    drawTriangle(x,y,order-1,t,size/2)
    """we must stop drawing so that we can cross from one stored point
    in the triangle to another on the other side"""
##    t.penup()
##    t.goto(x,y)
##    t.pendown()

#create a helper function
def drawTriangle(x,y,order,t, size):
    #we need to store the 3 separate (x,y) coordinate values for each
    #new triangle
    if order < 0: #not entirely sure about this number
        return 
    else:
        #step 1: draw upside down triangle
        #set position to x,y (automatically stored with each iteration)
        t.setposition(x,y)
        #^this code isn't working for some reason (t seems to be a float?)
        #setting (x,y) = to the moethod doesn't help

        t.forward(size)
        (x2, y2) = t.position()
        t.left(60)                 
        t.forward(size)  
        t.left(120)               
        t.forward(size)
        (x3, y3)=t.position()
        t.left(120)
        t.forward(size)

        #step 2: recursion - call drawTriangle 3x
        drawTriangle(x,y, order-1, size/2, t)
        drawTriangle(x2,y2, order-1, size/2, t)
        drawTriangle(x3,y3, order-1, size/2, t)

1 个答案:

答案 0 :(得分:-1)

在函数结尾,您在最后一次调用中的参数顺序似乎不正确。用这些行替换drawTriangle函数的最后几行:

def drawTriangle(x,y,order,t, size):
    ....
    drawTriangle(x,y, order-1, t, size/2)
    drawTriangle(x2,y2, order-1, t, size/2)
    drawTriangle(x3,y3, order-1, t, size/2)