Python,将迭代函数转换为递归函数 [英] Python, Make an iterative function into a recursive function
本文介绍了Python,将迭代函数转换为递归函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个迭代函数,该函数输出4 3 2 1 0 1 2 3 4.
I've created an iterative function which outputs 4 3 2 1 0 1 2 3 4.
def bounce2(n):
s = n
for i in range(n):
print(n)
n = n-1
if n <= 0:
for i in range(s+1):
print(-n)
n = n-1
return
bounce2(4)
如果我想要一个功能完全相同的递归函数,那我应该怎么想?
If I want a recursive function that does the exact same thing, how should I think?
推荐答案
尝试一下:
def bounce(n):
if n >= 0:
print(n)
bounce(n - 1)
if n:
print(n)
bounce(4)
输出将是: 4 3 2个 1个 0 1个 2个 3 4
the output will be: 4 3 2 1 0 1 2 3 4
这篇关于Python,将迭代函数转换为递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文