python - Python,将迭代函数变成递归函数
问题描述
我创建了一个迭代函数,它输出 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)
如果我想要一个做同样事情的递归函数,我应该怎么想?
解决方案
尝试这个:
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
推荐阅读
- json - 在 Bash 中对 JSON 记录进行分组和排序
- android - Jwplayer 不会同时播放多个视频
- java - 如何重新加载 JFrame?
- python - 从 AWS S3 存储桶引用对象时,无法执行 pandas read_excel 函数两次
- amazon-ecs - 如何在启动之前将文件复制到 docker 容器内的特定位置?
- python - 用 BeautifulSoup 刮掉同一个班级
- javascript - 根据过滤器更改按钮文本
- css - Litelement 组件样式 - :具有属性或类的主机
- apache-spark - Loading Parquet Files with Different Column Ordering
- javascript - How can I exclude multiple files from splitchunk webpack?