递归函数:在一原函数调用自身函数
经典实例:
二分查找法
二分查找法 l=[1,2,3,4,44,46,47,48,49,50,55,54,57,58,89,90,98] def star(l,aim,st=0,end=None): end=len(l) if end is None else end xde=(end - st)//2+st ai=l[xde] if aim in l: if ai<aim: return star(l,aim,st=xde+1,end=end) elif ai>aim: return star(l,aim,st=st,end=xde-1) else: return xde else: return("不在") ret=star(l,44) print(ret)View Code
斐波那契
斐波那契 1,1,2,3,5,8 def fib(n,l=[]): l[0]+=1 if n==1 or n==2: l[0] -= 1 return 1, 1 else: a,b=fib(n-1) l[0] -= 1 if l[0]==0: return a+b return b,a+b ret=fib(3) print(ret)View Code
阶乘
阶乘 3!3*2*1 def jie(n): if n==1: return 1 return n*jie(n-1) print(jie(1))View Code