Python递归问题;我无法将我的硬代码更改为递归函数

时间:2018-01-29 21:19:19

标签: python recursion

beside(picture,picture)         #beside takes two pictures as arguments and prints them side by side in a 1:1 ratio.

stackn(n,picture)         #stackn takes a number and a picture as arguments and prints n number of shapes in a vertical row.

show(picture)        #show takes a picture as an argument and shows it on the canvas

在这种情况下,图片是参数heart_bb

(n=2)#      show(beside((stackn(1,heart_bb)),(stackn(2,heart_bb))))

(n=3)#      show(beside((stackn(1,heart_bb)),(beside((stackn(2,heart_bb)),(stackn(4,heart_bb))))))

(n=4)#    show(beside((stackn(1,heart_bb)),(beside((stackn(2,heart_bb)),(beside((stackn(4,heart_bb)),(stackn(8,heart_bb))))))))

我的任务是提出一个递归函数(我将称之为测试):

def test(n, picture):

我需要这个函数来返回上面显示的相应代码行。例如,test(3,heart_bb)应该返回n=3的代码行。同样,test(4,heart_bb)将返回n=4的代码行。

它必须适用于任何n>1,但在n=5编码后,它变得非常繁琐。

def fractal(picture,n):
   if n==1:
       return(picture)

   else:
       return(beside((fractal(picture,(n-1))),(stackn((2**(n-1)),  (picture)))))

1 个答案:

答案 0 :(得分:0)

我想你主要需要知道如何做到这一点,而不是找到为你编写代码的人。 我建议使用n-ary beside操作代替你的操作,以简化n = 2,3,4的代码,...由于我无法修改它,我将定义一个以这种方式在二进制操作方面的新方法:

def beside_pictures(pictures):
    assert len(pictures) > 0
    result = pictures[-1]
    for tmp in pictures[:-1:-1]:  # reverse order, starting from -1
        result = beside(tmp, result)
    return result

现在我们准备在一行函数中转换您的测试函数:

def test(n, picture):
    assert n > 0
    show(beside_pictures([stackn(2**i,picture) for i in range(n)]))

更新:如果要求具有递归函数是严格的,一个可能的解决方案是以下一个:

def test(n, picture):
    if n == 1:
        return stackn(1,picture)
    return beside(test(n-1, picture), stackn(2**(n-1),picture))