Python3 standard library: bisect maintains an ordered list

1. bisect maintains an ordered list

bisect module implements an algorithm to insert into the list of elements, while still maintaining an ordered list.

Insert ordered 1.1

A simple example is given below, where the use insort () to insert elements into a list in an ordered sequence.

import bisect

# A series of random numbers
values = [14, 85, 77, 26, 50, 45, 66, 79, 10, 3, 84, 77, 1]

print('New  Pos  Contents')
print('---  ---  --------')

l = []
for i in values:
    position = bisect.bisect(l, i)
    bisect.insort(l, i)
    print('{:3}  {:3}'.format(i, position), l)

The first column shows the new output of the random number. The second round shows that the number of which will be inserted into the list. Each row is the rest of the current ordered list.

This is a very simple example, in fact, the amount of data processing in this embodiment, if the list is then constructed directly completing a sort may be faster. But for long lists, the use of a time like this insertion sort algorithm can greatly save time and memory, particularly members of the operation to compare two lists need significant computational overhead. 

1.2 Processing repeats

Before displaying the result set comprises a duplicate value 77. bisect module provides two ways to handle duplicate. The new value can be inserted to the left or right of the original value. insort () function is actually insort_right () alias, this function will insert a new value after the original value. Corresponding insort_left () function is the new value is inserted before the original value.

import bisect

# A series of random numbers
values = [14, 85, 77, 26, 50, 45, 66, 79, 10, 3, 84, 77, 1]

print('New  Pos  Contents')
print('---  ---  --------')

# Use bisect_left and insort_left.
l = []
for i in values:
    position = bisect.bisect_left(l, i)
    bisect.insort_left(l, i)
    print('{:3}  {:3}'.format(i, position), l)

When using bisect_left () and insort_left () processing the same data, the same result is an ordered list of values ​​is repeated but different insertion positions.

Guess you like

Origin www.cnblogs.com/liuhui0308/p/12342889.html