In [1]:
from bisect import bisect_left, bisect_right # for binary search
import random
random.seed(77) # so that you and I get same random lists
In [2]:
a = [1, 2, 3, 3, 3, 4, 5]
bisect_left(a, 3), bisect_right(a, 3)
Out[2]:
(2, 5)
In [3]:
a = [2, 4, 6, 8, 10]
bisect_left(a, 5), bisect_right(a, 5)
Out[3]:
(2, 2)
In [4]:
# make a list of pseudo-random integers in [1, 99]
ls = [ random.randint(1, 99) for _ in range(30) ]
ls # show it
Out[4]:
[33,
 42,
 26,
 31,
 25,
 15,
 38,
 61,
 72,
 79,
 31,
 19,
 72,
 81,
 85,
 65,
 1,
 36,
 4,
 64,
 23,
 25,
 65,
 50,
 24,
 43,
 42,
 16,
 12,
 71]
In [5]:
ls.sort() # sort the list in-place
ls # show the sorted list; note there are some repeated elements
Out[5]:
[1,
 4,
 12,
 15,
 16,
 19,
 23,
 24,
 25,
 25,
 26,
 31,
 31,
 33,
 36,
 38,
 42,
 42,
 43,
 50,
 61,
 64,
 65,
 65,
 71,
 72,
 72,
 79,
 81,
 85]
In [6]:
# The number 40 is not in the sorted list.  If it were, where would it go?
bisect_left(ls, 40)
Out[6]:
16
In [7]:
# insert it
ls.insert(13, 40)
ls # show the new list
Out[7]:
[1,
 4,
 12,
 15,
 16,
 19,
 23,
 24,
 25,
 25,
 26,
 31,
 31,
 40,
 33,
 36,
 38,
 42,
 42,
 43,
 50,
 61,
 64,
 65,
 65,
 71,
 72,
 72,
 79,
 81,
 85]
In [8]:
# The number 19 appears in the list multiple times.
# Say we want a range [st, en) where st is the first element
# (inclusive) and en is last element (exclusive) that contains a 19
st, en = bisect_left(ls, 19), bisect_right(ls, 19)
In [9]:
st, en
Out[9]:
(5, 6)
In [10]:
ls[st:en]
Out[10]:
[19]
In [11]:
# Of course, there also exists a total ordering over strings
# (lexicographical ordering), so we can do all the same things
# with strings
strls = ['a', 'awkward', 'awl', 'awls', 'axe', 'axes', 'bee']
In [12]:
strls == sorted(strls)
Out[12]:
True
In [13]:
# We want to get the range of elements that equal a query string:
st, en = bisect_left(strls, 'awl'), bisect_right(strls, 'awl')
st, en
Out[13]:
(2, 3)
In [14]:
# Say we want to get the range of elements that have some prefix,
# e.g. 'aw' and say that 'z' is the lexicographically greatest
# character in the alphabet.
st, en = bisect_left(strls, 'aw'), bisect_left(strls, 'ax')
st, en
Out[14]:
(1, 4)
In [15]:
strls[st:en]
Out[15]:
['awkward', 'awl', 'awls']
In [16]:
# If we can do it for any sorted list of strings, we can do it for
# a sorted list of suffixes
t = 'abaaba$'
suffixes = sorted([t[i:] for i in range(len(t))])
suffixes
Out[16]:
['$', 'a$', 'aaba$', 'aba$', 'abaaba$', 'ba$', 'baaba$']
In [17]:
st, en = bisect_left(suffixes, 'aba'), bisect_left(suffixes, 'abb')
st, en
Out[17]:
(3, 5)