Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 87c9d6c

Browse files
committed
Improve the docs for bisect to cover common searching tasks.
1 parent 1b66996 commit 87c9d6c

1 file changed

Lines changed: 57 additions & 3 deletions

File tree

Doc/library/bisect.rst

Lines changed: 57 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,16 +39,63 @@ The following functions are provided:
3939
``a.insert(bisect.bisect_left(a, x, lo, hi), x)``. This assumes that *a* is
4040
already sorted.
4141

42+
Also note that while the fast search step is O(log n), the slower insertion
43+
step is O(n), so the overall operation is slow.
44+
4245

4346
.. function:: insort_right(a, x, lo=0, hi=len(a))
4447
insort(a, x, lo=0, hi=len(a))
4548

4649
Similar to :func:`insort_left`, but inserting *x* in *a* after any existing
4750
entries of *x*.
4851

49-
50-
Examples
51-
--------
52+
Also note that while the fast search step is O(log n), the slower insertion
53+
step is O(n), so the overall operation is slow.
54+
55+
Searching Sorted Lists
56+
----------------------
57+
58+
The above :func:`bisect` functions are useful for finding insertion points, but
59+
can be tricky or awkward to use for common searching tasks. The following three
60+
functions show how to transform them into the standard lookups for sorted
61+
lists::
62+
63+
def find(a, key):
64+
'''Find item with a key-value equal to key.
65+
Raise ValueError if no such item exists.
66+
67+
'''
68+
i = bisect_left(a, key)
69+
if i < len(a) and a[i] == key:
70+
return a[i]
71+
raise ValueError('No item found with key equal to: %r' % (key,))
72+
73+
def find_le(a, key):
74+
'''Find largest item with a key-value less-than or equal to key.
75+
Raise ValueError if no such item exists.
76+
If multiple key-values are equal, return the leftmost.
77+
78+
'''
79+
i = bisect_left(a, key)
80+
if i < len(a) and a[i] == key:
81+
return a[i]
82+
if i == 0:
83+
raise ValueError('No item found with key at or below: %r' % (key,))
84+
return a[i-1]
85+
86+
def find_ge(a, key):
87+
'''Find smallest item with a key-value greater-than or equal to key.
88+
Raise ValueError if no such item exists.
89+
If multiple key-values are equal, return the leftmost.
90+
91+
'''
92+
i = bisect_left(a, key)
93+
if i == len(a):
94+
raise ValueError('No item found with key at or above: %r' % (key,))
95+
return a[i]
96+
97+
Other Examples
98+
--------------
5299

53100
.. _bisect-example:
54101

@@ -87,3 +134,10 @@ of the record in question::
87134
('red', 5)
88135
>>> data[bisect_left(keys, 8)]
89136
('yellow', 8)
137+
138+
.. seealso::
139+
140+
`SortedCollection recipe
141+
<http://code.activestate.com/recipes/577197-sortedcollection/>`_ that
142+
encapsulates precomputed keys, allowing straight-forward insertion and
143+
searching using a *key* function.

0 commit comments

Comments
 (0)