递归函数和二分查找
你想问A的年龄,A比B大两岁
B比C大两岁
C比D大两岁
D今年18
用递归做:
def func(n): if n==4: return 18 else: return func(n+1)+2 print(func())
求阶乘,用递归函数做:
def func(n): if n == 1: return 1 else: return func(n-1)*n print(func(4))
二分查找:
l=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31] def func(l,i,start=0,end=None): if end == None: end = len(l) - 1 if start <= end: mid = (end-start)//2+start if l[mid]>i: return func(l,i,start=start,end=mid-1) elif l[mid] <i: return func(l,i,start=mid+1,end=end) elif l[mid]==i: return mid else: return None print(func(l,10))
用递归函数写斐波那契数列:
#方法一 def func(n): if n==1: return 1 if n==2: return 1 else: return func(n-1)+func(n-2) print(func(35)) #由于该方法每次返回两个函数,计算量特别大,算到35 无法继续计算
#方法二 def fib(n,a=0,b=1): if n==1 or n==2: return a+b else: return fib(n-1,b,a+b) print(fib(34))
递归函数的三级菜单:
def menu3(menu): while True: for key in menu: print(key) choice=input("请选择城市") if choice in menu and menu[choice]: ret= menu3(menu[choice]) if ret =='q': return ret elif choice =='b'or choice=='q': return choice menu3(menu)