Add comparison between iteration and recursion.

Fix the figure of tail recursion.
Fix two links.
This commit is contained in:
krahets
2023-09-12 00:56:59 +08:00
parent 2b54352bec
commit 5f814d6538
7 changed files with 184 additions and 10 deletions

View File

@ -16,6 +16,23 @@ def recur(n: int) -> int:
return n + res
def for_loop_recur(n: int) -> int:
"""使用迭代模拟递归"""
# 使用一个显式的栈来模拟系统调用栈
stack = []
res = 0
# 递:递归调用
for i in range(n, 0, -1):
# 通过“入栈操作”模拟“递”
stack.append(i)
# 归:返回结果
while stack:
# 通过“出栈操作”模拟“归”
res += stack.pop()
# res = 1+2+3+...+n
return res
def tail_recur(n, res):
"""尾递归"""
# 终止条件
@ -42,6 +59,9 @@ if __name__ == "__main__":
res = recur(n)
print(f"\n递归函数的求和结果 res = {res}")
res = for_loop_recur(n)
print(f"\n使用迭代模拟递归求和结果 res = {res}")
res = tail_recur(n, 0)
print(f"\n尾递归函数的求和结果 res = {res}")