1. 程式人生 > >2.8章 bisect 模塊介紹

2.8章 bisect 模塊介紹

ntp python .org and lib name true ocs 返回

1,用bisect 來搜索,內部算法就是二分查找法,時間復雜度O(log?n)

##先看一個簡單使用的例子

import bisect
import random

L = list(range(20))
# print(L) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

find_value0 = bisect.bisect(L, 5)
print(find_value0)  # 6 默認是返回查到到的值的右邊的索引

find_value1 = bisect.bisect_left(L, 5)
print(find_value1)  # 5  和list 內置方法index結果一樣,區別是算法不同,官方文檔推薦:在重大的list查找值時使用bisect

find_value2 = L.index(5)
print(find_value2)  # 5  線性查找 O(logn)

  ##FluentPython 的例子

import bisect
import sys

HAYSTACK = [1, 4, 5, 6, 8, 12, 15, 20, 21, 23, 23, 26, 29, 30]
NEEDLES = [0, 1, 2, 5, 8, 10, 22, 23, 29, 30, 31]

ROW_FMT = ‘{0:2d} @ {1:2d}    {2}{0:<2d}‘   # 這是格式化輸出語法,(:表示取位數, < 表示左對齊)

def demo(bisect_fn):
    for needle in reversed(NEEDLES):
        position = bisect_fn(HAYSTACK, needle)  # <1>

        offset = position * ‘  |‘  # <2>

        print(ROW_FMT.format(needle, position, offset))  # <3>

if __name__ == ‘__main__‘:

    if sys.argv[-1] == ‘left‘:    # 在命令行執行python文件的時候可以後面加一個參數(加的參數會以列表形式被程序接收) 這裏可以加left,執行的時候就掉用bisect_left這個api
        bisect_fn = bisect.bisect_left
    else:
        bisect_fn = bisect.bisect

    print(‘DEMO:‘, bisect_fn.__name__)  # <5>
    print(‘haystack ->‘, ‘ ‘.join(‘%2d‘ % n for n in HAYSTACK))
    demo(bisect_fn)

輸出結果:

DEMO: bisect
haystack ->  1  4  5  6  8 12 15 20 21 23 23 26 29 30
31 @ 14      |  |  |  |  |  |  |  |  |  |  |  |  |  |31
30 @ 14      |  |  |  |  |  |  |  |  |  |  |  |  |  |30
29 @ 13      |  |  |  |  |  |  |  |  |  |  |  |  |29
23 @ 11      |  |  |  |  |  |  |  |  |  |  |23
22 @  9      |  |  |  |  |  |  |  |  |22
10 @  5      |  |  |  |  |10
 8 @  5      |  |  |  |  |8 
 5 @  3      |  |  |5 
 2 @  1      |2 
 1 @  1      |1 
 0 @  0    0 

格式化字符串

官方文檔介紹

2,bisect.insort() 向列表中插入值

def wahaha(size):
    mylist = []
    for m in range(size):
        newitem = random.randrange(size * 2)
        bisect.insort(mylist, newitem)
        print(‘%5d ->‘ % newitem, mylist)

wahaha(10)

 輸出:

   14 -> [14]
    0 -> [0, 14]
   15 -> [0, 14, 15]
   17 -> [0, 14, 15, 17]
   18 -> [0, 14, 15, 17, 18]
   15 -> [0, 14, 15, 15, 17, 18]
   14 -> [0, 14, 14, 15, 15, 17, 18]
   12 -> [0, 12, 14, 14, 15, 15, 17, 18]
    6 -> [0, 6, 12, 14, 14, 15, 15, 17, 18]
   13 -> [0, 6, 12, 13, 14, 14, 15, 15, 17, 18]

  

2.8章 bisect 模塊介紹