小白學python--二分尋找法

來源:互聯網
上載者:User

標籤:學python   binary   ice   div   一個   比較   輸出   通過   while   

二分尋找:通過對待尋找的值與有序列表的中間值進行比較,輸出尋找結果。

時間複雜度為:Olog(n)

#二分法尋找學號,並列印出這一個學號學生的資訊import randomdef random_list(n):#產生具有學號、年齡、姓名的列表    result=[]    ids=list(range(1001,1001+n))    a1=[‘趙‘,‘錢‘,‘孫‘,‘李‘,‘周‘,‘吳‘,‘鄭‘,‘王‘]    a2=[‘紅‘,‘橙‘,‘黃‘,‘綠‘,‘青‘,‘藍‘,‘紫‘]    a3=[‘強‘,‘國‘,‘秒‘,‘曼‘,‘萌‘,‘霞‘,‘娟‘,‘莎‘]    for i in range(n):        age=random.randint(18,20)        id=ids[i]          
name=random.choice(a1)+random.choice(a2)+random.choice(a3) result.append({"id":id,"age":age,"name":name}) return resultdef Binary_search(List,val):#尋找符合要求的學號 low=0 high=len(List)-1 while low<=high: mid=(low+high)//2 if List[mid][‘id‘]==val: print(List[mid]) return mid elif List[mid]["id"]<val: low=mid+1 else: high=mid-1 print("裡面沒有")#只有在查不到的情況下才會執行這條指令List=random_list(100)val_dict=1070Binary_search(List,val_dict)

 

小白學python--二分尋找法

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.