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

2024-04-24 18:37:29 发布

您现在位置:Python中文网/ 问答频道 /正文

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和picture,并以如下所示的模式将其打印到画布上。在

^{pr2}$

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的初学者,所以我非常感谢能得到的任何帮助!在


Tags: ofthe代码onshowoneeachother
1条回答
网友
1楼 · 发布于 2024-04-24 18:37:29

您可以简单地执行以下操作:

def fractal(picture,n):
   if n == 1:
       return(picture)
   else:
       return(beside(picture, stack(2, fractal(picture,(n-1)))))

代码的意思是,如果n是1,则返回图片。 否则,把两张更小的照片放在另一张上面,放在一张图片旁边,然后继续。在

您可以创建一些帮助函数来使代码更清晰,例如

^{pr2}$

相关问题 更多 >