Python bisect模塊原理及常見實例
1. 模塊介紹
1. bisect模塊為內置標準庫,它實現(xiàn)了二分法查找算法(只要提到二分法查找,應該優(yōu)先想到此模塊)
2. 主要包含有兩個函數(shù):bisect函數(shù)(查找元素)和insort函數(shù)(插入元素)。
2. 常用方法介紹
場景1:已知一個有序列表,查找目標元素的位置索引
import bisect# 已知一個有序序列ordered_list = [23, 34, 59, 78, 99]des_element = 21res = bisect.bisect(ordered_list, des_element)print(res) # res: 0des_element = 35res = bisect.bisect(ordered_list, des_element)print(res) # res: 2
說明:bisect函數(shù)會默認返回右側的位置索引,同時bisect函數(shù)是bisect_right函數(shù)的別名。
場景2:已知一個有序列表,其中列表中有重復元素,查找目標元素的位置索引
import bisect# 已知一個有序序列ordered_list = [23, 34, 34, 59, 78, 99]# bisect函數(shù)默認返回右側的位置索引des_element = 34res = bisect.bisect(ordered_list, des_element)print(res) # res: 3# bisect函數(shù)為bisect_right函數(shù)的別名des_element = 34res = bisect.bisect_right(ordered_list, des_element)print(res) # res: 3# bisect_left函數(shù)默認返回左側的位置索引des_element = 34res = bisect.bisect_left(ordered_list, des_element)print(res) # res: 1
說明:如果目標元素會在已知有序列表中多次出現(xiàn),那么目標元素從已知有序列表的左側或右側插入時結果是不同的。
3. 場景應用
場景1:替代if-elif語句,例如:判斷考生成績所屬的等級問題。
’’’ 考試成績的檔位劃分,共分為5個等級: 1. F等級:[0, 60) 2. D等級:[60, 70) 3. C等級:[70, 80) 4. B等級:[80, 90) 5. A等級:[90, 100]’’’import bisectdef get_result(score: (int, float), score_nodes: list = [60, 70, 80, 90], ranks=’FDCBA’) -> str: # 校驗:分數(shù)范圍 if score < 0 or score >100: return 'score的取值范圍:0-100' # 邊界點考慮 if int(score) == 100: return 'A' loc_index = bisect.bisect(score_nodes, score) return ranks[loc_index]print(get_result(50)) # res: Fprint(get_result(60)) # res: Dprint(get_result(85.5)) # res: Bprint(get_result(100)) # res: A
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
1. 詳解Android studio 動態(tài)fragment的用法2. 編程語言PHP在Web開發(fā)領域的優(yōu)勢在哪?3. 什么是python的自省4. Spring Boot和Thymeleaf整合結合JPA實現(xiàn)分頁效果(實例代碼)5. 解決Android studio xml界面無法預覽問題6. 基于android studio的layout的xml文件的創(chuàng)建方式7. Android如何加載Base64編碼格式圖片8. Springboot Druid 自定義加密數(shù)據(jù)庫密碼的幾種方案9. Vue封裝一個TodoList的案例與瀏覽器本地緩存的應用實現(xiàn)10. 圖文詳解vue中proto文件的函數(shù)調用

網公網安備