function - 我应该如何阅读有关递归的代码?
问题描述
我应该如何阅读这段代码?
if n <= 0:
return ''
else:
temp = repeatStar(n-1)
s = '*' + temp
return s
a = 4
res = repeatStar(a)
print(res)
我不再理解的部分是 repeatStar(n-1) 部分。它将重复该函数,直到 n == 0,然后返回 ''。但那么所有的星星是从哪里来的呢?s = '*' + 温度。所以那应该是'*'+''对吗?我究竟做错了什么?
对不起,如果我没有很好地解释它
解决方案
这样想,运行这个你总是会看到星星的数量等于输入值。
这是为什么?
让我们看一下您提供的输入为 4 的情况:
您使用输入 n = 4 调用该函数,它会检查 if 语句,然后转到 else 块,初始化 temp,它会尝试计算“repeatStar(4-1)”
您使用输入 n = 3 调用该函数,它检查 if 语句,然后转到 else 块,初始化 temp,它尝试计算“repeatStar(3-1)”
您使用输入 n = 2 调用该函数,它检查 if 语句,然后转到 else 块,初始化 temp,它尝试计算“repeatStar(2-1)”
您使用输入 n = 1 调用该函数,它检查 if 语句,然后转到 else 块,初始化 temp,它尝试计算“repeatStar(1-1)”
您使用输入 n = 0 调用该函数,它会检查 if 语句然后转到 return empty_string
现在将 temp 设为 (empty_string),分配 s ('*' + empty_string) 并返回
现在将 temp 设为 ('*' + empty_string),分配 s ('*' + '*' + empty_string) 并返回
现在将 temp 设为 ('*' + '*' + empty_string'),分配 s ('*' + '*' + '*' + empty_string') 并返回
现在将 temp 设为 ('*' + '*' + '*' + empty_string'),分配 s ('*' + '*' + '*' + '*' + empty_string')
现在堆栈被清空,我们打印结果'****'
推荐阅读
- google-cloud-platform - 识别比较句
- javascript - 无法通过不完整的名称获取频道 twillio programmabale 聊天节点 js
- flutter - ScopedModel - 如何传递多个模型
- python - 突然无法在 Google Colab 中更改 Python 版本的运行时
- java - 如何使用 redisson 客户端获取缓存值
- ruby-on-rails - 使用inf Rspec测试控制器时出现UrlGenerationError
- docker - Traefik - 角度应用程序的后端代理
- grails - 如何使用 .gsp 文件在 grails 应用程序中以可编辑模式隐藏字段?
- javascript - 在 mongoose 中创建带有 { strict: false } 的文档
- reactjs - jsencrypt 使用公钥加密的替代方案