laide_teacher_python/20240709递归.py

28 lines
655 B
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 数列
# 13579
def fibonacci(n):
if n <= 1: # 基本情况第1项和第2项都是1
return n
else: # 递归情况第n项是前两项的和
return fibonacci(n - 1) + fibonacci(n - 2)
# n = 3
# n = 2
# n=1 结果1
# n=0 结果0
# 结果 1
# n = 1 结果1
# 结果 2
print(fibonacci(6))
# 阶乘 5的阶乘5*4*3*2*1
# 基本情况n==1, 返回1
# 递归过程n*f(n-1)
# 8的阶乘
# ---------------------------------
# n项的数列1,2,3,4,5,6,7,8......
# 使用递归求前n项数值的和
# 基本情况n==1
# 递归过程n+f(n-1)
# 前10项的和