递归的定义:
在函数内部直接或者间接调用函数本身
递归的应用:
△求一个数的阶乘
1 def jiecheng(n): 2 if n == 1: 3 return 1 4 else: 5 return n*jiecheng(n-1) 6 print(jiecheng(4))
△求第几个斐波那契数
1 def f(n): 2 if n == 2: 3 return 1 4 elif n ==1: 5 return 1 6 else: 7 return f(n-1)+f(n-2) 8 print(f(33))
△二分法查找
1 l = [1,3,5,6,11,13,15,17,21,32,36,52,56,58,66,77,88,99] 2 def find(l,n,start=0,end=None): 3 end = len(l) if end is None else end 4 mid_index = (end-start)//2 + start 5 if start>=end: 6 return ‘找不到‘ 7 else: 8 if n>l[mid_index]: 9 return find(l,n,mid_index+1,end) 10 elif n<l[mid_index]: 11 return find(l,n,start,mid_index-1) 12 else:return mid_index 13 14 res = find(l,17) 15 print(res)