1

我需要编写一个函数 spin(pic,x) 它将拍照并逆时针旋转 90 度 X 次。我在一个函数中只有 90 度顺时针旋转:

def rotate(pic):
    width = getWidth(pic)
    height = getHeight(pic)
    new = makeEmptyPicture(height,width)
    tarX = 0
    for x in range(0,width):
        tarY = 0
        for y in range(0,height):
            p = getPixel(pic,x,y)
            color = getColor(p)
            setColor(getPixel(new,tarY,width-tarX-1),color)
            tarY = tarY + 1
        tarX = tarX +1
    show(new)
    return new

..但我不知道如何编写一个旋转X次的函数。有谁知道我该怎么做?

4

1 回答 1

0

您可以调用rotate()X 次:

def spin(pic, x):
    new_pic = duplicatePicture(pic)
    for i in range(x):
         new_pic = rotate(new_pic)
    return new_pic


a_file = pickAFile()
a_pic = makePicture(a_file)
show(spin(a_pic, 3))

但这显然不是最优化的方法,因为您将计算 X 图像而不是您感兴趣的图像。我建议您首先尝试一种基本switch...case方法(即使 Python 中不存在此语句;):

xx = (x % 4)     # Just in case you want (x=7) to rotate 3 times...

if (xx == 1):
    new = makeEmptyPicture(height,width)
    tarX = 0
    for x in range(0,width):
        tarY = 0
        for y in range(0,height):
            p = getPixel(pic,x,y)
            color = getColor(p)
            setColor(getPixel(new,tarY,width-tarX-1),color)
            tarY = tarY + 1
        tarX = tarX +1
    return new
elif (xx == 2):
    new = makeEmptyPicture(height,width)
    # Do it yourself...
    return new
elif (xx == 3):
    new = makeEmptyPicture(height,width)
    # Do it yourself...
    return new
else:
    return pic

然后,也许您将能够看到一种将这些案例合并为一个(但更复杂)的方法double for loop......玩得开心......

于 2013-10-31T04:24:19.120 回答