python递归如何将硬代码转换为递归函数

时间:2018-01-29 22:55:42

标签: python recursion

beside(picture,picture) # stacks 2 pictures beside each other, with the first one on the left, and the second one on the right.

stackn(n,picture) # stacks n number of pictures on top of each other in a vertical line

show(picture) # prints the whole picture on the canvas

我的任务的目的是创建一个函数,它接受2个参数n和图片,并将其打印到画布中的图案,如下所示。

test(n,picture)

enter image description here

(这是n = 4)

这是我到目前为止所提出的。

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

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

但是这段代码会产生这种代码。

enter image description here

以下代码行是解决方案的硬代码版本。

(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))))))))

我是python的初学者,所以我真的很感激我能得到任何帮助!

1 个答案:

答案 0 :(得分:0)

你可以这样做:

def stacktwo(picture):
    return stack(2, picture)

def fractal(picture,n):
   if n == 1:
       return(picture)
   else:
       smaller = fractal(picture, (n-1))
       return(beside(picture, stacktwo(smaller)))

代码的含义是,如果n为1则返回自己的图片。 否则,将两张较小的照片放在另一张照片的顶部,然后将它们放在一张照片旁边,然后继续拍摄。

您可以创建一些帮助功能,使您的代码更加清晰,例如

{{1}}