什么是函数递归
函数的嵌套调用是函数嵌套函数,函数递归就是特殊的嵌套调用,他在调用一个函数的过程中又直接或间接地调用了它自身.通俗讲就是函数A调用了函数A
count=0
def f1():
global count #下面的count是全局的count
count+=1
print(count)
f1()
f1()
#报错,调用时超过最大递归深度,函数自动终止循环
递归的核心
递进时可以达到一个结果,问题规模越来越小(不一定要真正的达到);设置一个条件,能够让最后一次函数调用结束
递归必须要有两个明确的阶段
- 递推:一层一层递归调用下去,进入下一层递归的问题规模都将会减小.
- 回溯:递归必须要有一个明确的结束条件,在满足该条件开始一层层回溯.
递归的精髓在于通过不断地重复逼近一个最终的结果,它更多的是一种思想,用于解决某些问题
count=0
def f1():
global count #下面的count是全局的count
if count>100:
return
count+=1
print(count)
f1()
f1()
用递归求年龄
16/18/20/22/24/26
第一个人的年龄是16,我要求出5个人后的年龄-->26
age=16
def age_func(x): # age_func(5) = age_func(4) = age_func(3) = age_func(2) = age_func(1) = age_func(0) =26
global age # x的规模在减小 # x = 5 # x =4 # x =3 # x =2 # x = 1 # x = 0
if x==0:
return age # 终止函数,age=26,这是age_func(0)
age+=2 # age = 18 # age = 20 # age 22 # age = 24 # age = 26
return age_func(x-1) # age_func(4) # age_func(3) # age_func(2) # age_func(1) # age_func(0)
res=age_func(5)
print(res) #26
'''
age_func(5) --> age = 18 --> return age_func(4) # return 26
age_func(4) --> age = 20 --> return age_func(3)
age_func(3) --> age = 22 --> return age_func(2)
age_func(2) --> age = 24 --> return age_func(1) == return age_func(0) == return age == return 26
age_func(1) --> age = 26 --> return age_func(0) == return age == return 26
return age # age = 26
'''
#另一种写法
age=16
def age_func(x):
global age
if x==0:
return age
return age_func(x-1)+2
res=age_func(5)
print(res)
'''
age_func(5) --> return age_func(4)+2 == 24+2 =26
age_func(4) --> return age_func(3)+2 == 22+2 = 24
age_func(3) --> return age_func(2)+2 == 20+2 = 22
age_func(2) --> return age_func(1)+2 == 18+2 = 20
age_func(1) --> return age_func(0)+2 == 16+2= 18
'''