測試第二個月:演算法
阿新 • • 發佈:2020-12-16
斐波那契:
def fun(i): if i == 0: return 0 elif i == 1: return 1 else: return fun(i-2)+fun(i-1) if __name__ == '__main__': for i in range(10): print(fun(i),end=" ")
直角三角形:
for i in range(6): i += 1 for j in range(i): print('*', end='') print()
等邊三角形:
for i in range(1,6): for j in range(1,6-i): print(" ",end="") print("* "*i)
for i in range(1,6): for j in range(1,6-i): print(" ",end="") for k in range(1,i+1): print("* ",end="") print("")
選擇排序:
def func(alist): # x就是1到傳過來的這個引數的總長度 forx in range(0,len(alist)): # min_num 就等於每次迴圈的小標對應數字 min_num = alist[x] # 迴圈小標x+1 到所有下標長度 for i in range(x+1,len(alist)): # 如果下標i的引數大於min_num if alist[i] < min_num: # 互換位置(引數互換) alist[i],min_num = min_num,alist[i] alist[x]= min_num return alist print(func([1,55,22,66,44,22,88]))
氣泡排序:
def func(alist):
for x in range(1,len(alist)): # x 就是 1 到 傳過來的這個引數的長度總值
for i in range(0,len(alist)-x): # i 就是 傳過來的列表長度 - 去 x
if alist[i] > alist[i+1]: # 如果下標i 小於i+1
alist[i], alist[i+1] = alist[i+1], alist[i] # 那麼 下標i 與 下標 i+1 互換位置
return alist # 返回排序後的列表
print(func([1,4,2,3,6,7,8,9,0,5])) # 輸出 func([1,4,2,3,6,7,8,9,0,5]) 這句話就是 向func函式中傳遞引數
二分查詢:
def binnry_search(alist,item): # 構造初始下標和結束下標 first = 0 last = len(alist)-1 # 構造迴圈比較條件 while first <= last: # 構造中間值下標 mid = (first+last) // 2 # item (要查詢的元素) 和中間值下標對應的元素進行比較 查詢到後直接返回值 if item == alist[mid]: # 返回查詢到的值 return True,alist.index(item) else: if item > alist[mid]: first = mid + 1 else: last = mid - 1 return False if __name__ == '__main__': a_list = [-22,-11,0,11,22,33,38,44,55,57,66,72,81,96,123456] print(binnry_search(a_list,44))
通過迭代查詢中間值:
def fun(alist,item): if len(alist) == 0: return False else: mid = len(alist) // 2 #獲取中間值的下標 if item == alist[mid]: return True,item elif item < alist[mid]: # 如果查詢的數小於中間值 return fun(alist[:mid],item) #從開頭到中間值查詢 [:mid]是中間值66往前得數 else: return fun(alist[mid+1:],item) # 否則從中間值下一個數到結尾 # 輸出返回的值 print(fun([1, 22,33,44,55,66,77,88,99],66))
二分法:
def func(alist, item): low = 0 high = len(alist)-1 n = 0 while low <= high: mid = int((low + high)/2) n += 1 if alist[mid]==item: return mid if alist[mid]<item: low = mid + 1 else: high = (mid-1) return None m=[1,2,3,4,8,9,11,12,14,18,19,20,28] print(func(m,14))