首页 > 解决方案 > 我应该如何阅读有关递归的代码?

问题描述

我应该如何阅读这段代码?

  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 = '*' + 温度。所以那应该是'*'+''对吗?我究竟做错了什么?

对不起,如果我没有很好地解释它

标签: functionrecursion

解决方案


这样想,运行这个你总是会看到星星的数量等于输入值。

这是为什么?

让我们看一下您提供的输入为 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')

现在堆栈被清空,我们打印结果'****'


推荐阅读