python學習day17 遞迴函式
阿新 • • 發佈:2018-11-05
遞迴函式
http://www.cnblogs.com/Eva-J/articles/7205734.html
def age(n): if n == 4: return 40 elif n >0 and n < 4: return age(n+1) + 2 print(age(1)) # 46
只要寫遞迴函式,必須要有結束條件。
二分法查詢
l = [2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,76,82,83,88]def find(l,aim,start = 0,end = None): end = len(l) if end is None else end mid_index = (end - start)//2 + start ## 注意這個! if start <= end: if l[mid_index] < aim: return find(l,aim,start =mid_index+1,end=end) elif l[mid_index] > aim: return find(l, aim, start=start, end=mid_index-1)else: return mid_index else: return '找不到這個值' ret= find(l,67) print(ret) # 18
斐波那契
# 斐波那契 # 問第n個斐波那契數是多少 # 1,1,2,3,5,8 #fib(6) = fib(5) + fib(4) def fibn(n): if n==1 or n==2: return 1 else: return fibn(n - 1) +fibn(n - 2) # 一般情況下 避免使用雙遞迴
階乘
def fac(n): if n==1: return 1 else: return n*fac(n-1)