python演算法 二分查詢法

2022-02-10 04:12:27 字數 1833 閱讀 9772

import

random

defrandom_list(n):

result =

ids = list(range(1001,1001+n))

a1 = ["

趙","

錢","

孫","

李","

周","

吳","

鄭","

王","

馮","

陳","

褚","

衛","

蔣","

沈","

韓","

楊","

朱","

秦","

尤","

許","

何","

呂","

施","張"

] a2 = ["","

明","

俊","

辭","

澤","

鵬","

振","

鎮","

苗","

華","

國","

澄","

邈","

德","

澤","

海","

超","

曦","

陽","

榮","

逸","

昌","

鈺","玥""

菲","

雯","

嘉","

麟","

芸","

希","瀚"

] a3 = ["

克","

智","

誠","

宇","

華","","

傑","

天","

鋒","

巍","

榮","

凱","

海","

瑤","

涵","

雅","

晨","

曦","

麟","

煒","

茜","

萱","

玥","

菲","

雯","

嘉","

麟","

芸","

希","瀚"

]

for i in

range(n):

age = random.randint(18,60)

id =ids [i]

name = random.choice(a1)+random.choice(a2)+random.choice(a3)

dict =

return

result

'''輸入學生id,輸出該學生在列表中的下標,並輸出完整學生資訊

'''def

bin_search(data_set,val):

low =0

high = len(data_set) - 1

while low <=high :

mid = (low + high) // 2

if data_set[mid]["

id"] ==val:

return

data_set[mid]

elif data_set[mid]["

id"] >val:

high = mid - 1

else

: low = mid + 1

return

userlist = random_list(100)

u = bin_search(userlist,1051)

print(u)

演算法 二分查詢法

例題 設計乙個函式,接收乙個有序陣列和乙個元素,如果指定的元素包含在陣列中,則返回其位置。看見這道題,我們正常的想法為遍歷陣列的所有元素然後乙個乙個的與數值相比較,如果相等,返回索引,如果在迴圈執行完後沒有退出函式的話,就返回false。為 var count 0 計數 function looku...

查詢演算法 二分查詢法

二分查詢法是經典的入門演算法,以高效和廣泛應用而著稱.演算法是由靜態方法rank 實現的,它接受乙個整數鍵和乙個已經有序的int 陣列作為引數。如果該鍵存在於陣列中 則返回它的索引,否則返回 1。演算法使用兩個變數low 和high,並保證如果鍵在陣列中則它一定在 a low high 中,然後方法...

python查詢演算法 二分法

二分法是一種快速查詢的方法,時間複雜度低,邏輯簡單易懂,總的來說就是不斷的除以2除以2.例如需要查詢有序陣列arr裡面的某個關鍵字key的位置,那麼首先確認arr的中位數或者中點center,下面分為三種情況 12 3假如arr center key,說明key在arr中心左邊範圍 假如arr ce...