python_bisect模塊的使用


這個模塊只有幾個函數,

一旦決定使用二分搜索時,立馬要想到使用這個模塊 

 

[python]  view plain  copy
 
 print?
  1. import bisect  
  2.   
  3. L = [1,3,3,6,8,12,15]  
  4. x = 3  
  5.   
  6. x_insert_point = bisect.bisect_left(L,x)  #在L中查找x,x存在時返回x左側的位置,x不存在返回應該插入的位置..這是3存在於列表中,返回左側位置1  
  7. print x_insert_point  
  8.   
  9. x_insert_point = bisect.bisect_right(L,x)  #在L中查找x,x存在時返回x右側的位置,x不存在返回應該插入的位置..這是3存在於列表中,返回右側位置3  
  10.   
  11. print x_insert_point  
  12.   
  13. x_insort_left = bisect.insort_left(L,x)  #將x插入到列表L中,x存在時插入在左側  
  14. print L  
  15.   
  16. x_insort_rigth = bisect.insort_right(L,x) #將x插入到列表L中,x存在時插入在右側      
  17.   
  18. print L  


結果:

 

1
3
[1, 3, 3, 3, 6, 8, 12, 15]
[1, 3, 3, 3, 3, 6, 8, 12, 15]

實際使用中

[python]  view plain  copy
 
 print?
    1. bisect.insort_left與 bisect.insort_right 差別不大,作用基本相同 。。。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM