The role of bisect module

1. It bisectis used to process the sorted sequence, that is, to maintain the sorted ascending sequence.

In the source bisect.pyfile, it structureis: insort, bisect, insort_right, insort_left, bisect_right, bisect_left. Roughly implement insert operation and search operation (two points used).

import bisect
#二分查找
inter_list = []
bisect.insort(inter_list, 3)
bisect.insort(inter_list, 2)
bisect.insort(inter_list, 5)
bisect.insort(inter_list, 1)
bisect.insort(inter_list, 6)

print(inter_list) # [1,2,3,5,6]

You can see that what is returned is a complete sort sequence.

Now we want to insert a new data and find its position in the sequence.

# [1, 2, 3, 5, 6]
print(bisect.bisect(inter_list, 3))
# 3 
# 在序列下标为3的位置插入

The bisectdefault bisect_rightmethod in the source code . That is, the next position of the repeated element.

bisect_leftIt is inserted at the previous position of the repeated element.

# [1, 2, 3, 5, 6]
print(bisect.bisect_left(inter_list, 3))
# 2

2. Subsection

It was inter_list = []not just a list that was defined at the beginning , but any sequence type that can be modified can actually be used. For example, a deque.

import bisect
from collections import deque

inter_list = deque()

bisect.insort(inter_list, 3)
bisect.insort(inter_list, 2)
bisect.insort(inter_list, 5)
bisect.insort(inter_list, 1)
bisect.insort(inter_list, 6)

print(bisect.bisect_left(inter_list, 3))
print(inter_list)

# 2
# deque([1, 2, 3, 5, 6])

Guess you like

Origin blog.csdn.net/weixin_43901214/article/details/106978866