1. 程式人生 > >python 基礎---遞歸

python 基礎---遞歸

n-2 tar spa color 斐波拉契 -s nbsp pytho 階乘

 1 # 二分查找算法 必須處理有序的列表
 2 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]
 3 #print(l.index(66))
 4 
 5 # 代碼實現
 6 def find(l,aim,start = 0,end = None):
 7     end = len(l) if end is None else end
 8     mid_index = (end - start)//2 + start
 9     if start <= end:
10         if
l[mid_index] < aim: 11 return find(l,aim,start =mid_index+1,end=end) 12 elif l[mid_index] > aim: 13 return find(l, aim, start=start, end=mid_index-1) 14 else: 15 return mid_index 16 else: 17 return 找不到這個值 18 19 ret= find(l,66)
20 print(ret)
 1 #斐波拉契
 2 def fib(n):
 3     if n == 1 or n == 2:
 4         return 1
 5     else:
 6         return fib(n-1) + fib(n-2)
 7 
 8 print(fib(5))
 9 
10 def fib(n):
11     if n == 2:
12         return 1,1
13     else:
14         a,b = fib(n-1)
15         return b,a+b
16 print(fib(5))
#
階乘 def fac(n): if n ==1: return 1 return n*fac(n-1)

python 基礎---遞歸