二分查找與斐波那契
阿新 • • 發佈:2018-08-23
斐波那契 dex earch exit else find fib python its
二分查找
l=[1,2,10,30,33,99,101,200,301,311,402,403,500,900,1000] def search(n,l): if len(l) == 1: print("not exit") return index = len(l)//2 if n > l[index]: l = l[index+1:] search(n,l) elif n < l[index]: l = l[:index] search(n,l) else: print("find it") search(200,l)
def search(n,l,start=0,stop=len(l)-1): if start <= stop: mid = start + (stop-start) // 2 print(‘start:[%s] stop:[%s] mid:[%s] mid_val:[%s]‘ % (start, stop, mid, l[mid])) if n > l[mid]: start = mid + 1 elif n < l[mid]: stop = mid - 1 else: print("find it") return search(n,l,start,stop) else: print("not exits") search(10,l)
斐波那契
非遞歸
def fib(n):
a,b = 0,1
while a < n:
print(a,end=" ")
a,b = b,a+b
fib(100)
遞歸
def fib(a,b,stop):
if a > stop:
return
print(a,end=" ")
fib(b,a+b,stop)
fib(0,1,100)
二分查找與斐波那契