blob: 8bf0949597603492765370a53f1c7ceb841359b7 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`bisect` --- Array bisection algorithm
2===========================================
3
4.. module:: bisect
5 :synopsis: Array bisection algorithms for binary searching.
6.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
Raymond Hettinger20933e02010-09-01 06:58:25 +00007.. sectionauthor:: Raymond Hettinger <python at rcn.com>
Christian Heimes5b5e81c2007-12-31 16:14:33 +00008.. example based on the PyModules FAQ entry by Aaron Watters <arw@pythonpros.com>
Georg Brandl116aa622007-08-15 14:28:22 +00009
10This module provides support for maintaining a list in sorted order without
11having to sort the list after each insertion. For long lists of items with
12expensive comparison operations, this can be an improvement over the more common
13approach. The module is called :mod:`bisect` because it uses a basic bisection
14algorithm to do its work. The source code may be most useful as a working
15example of the algorithm (the boundary conditions are already right!).
16
17The following functions are provided:
18
19
Georg Brandl0d8f0732009-04-05 22:20:44 +000020.. function:: bisect_left(a, x, lo=0, hi=len(a))
Georg Brandl116aa622007-08-15 14:28:22 +000021
Raymond Hettinger20933e02010-09-01 06:58:25 +000022 Locate the insertion point for *x* in *a* to maintain sorted order.
Georg Brandl0d8f0732009-04-05 22:20:44 +000023 The parameters *lo* and *hi* may be used to specify a subset of the list
24 which should be considered; by default the entire list is used. If *x* is
25 already present in *a*, the insertion point will be before (to the left of)
26 any existing entries. The return value is suitable for use as the first
Raymond Hettinger20933e02010-09-01 06:58:25 +000027 parameter to ``list.insert()`` assuming that *a* is already sorted.
Georg Brandl116aa622007-08-15 14:28:22 +000028
Raymond Hettinger20933e02010-09-01 06:58:25 +000029 The returned insertion point *i* partitions the array *a* into two halves so
30 that ``all(val < x for val in a[lo:i])`` for the left side and
31 ``all(val >= x for val in a[i:hi])`` for the right side.
Georg Brandl116aa622007-08-15 14:28:22 +000032
Georg Brandl0d8f0732009-04-05 22:20:44 +000033.. function:: bisect_right(a, x, lo=0, hi=len(a))
34 bisect(a, x, lo=0, hi=len(a))
Georg Brandl116aa622007-08-15 14:28:22 +000035
Georg Brandl0d8f0732009-04-05 22:20:44 +000036 Similar to :func:`bisect_left`, but returns an insertion point which comes
37 after (to the right of) any existing entries of *x* in *a*.
Georg Brandl116aa622007-08-15 14:28:22 +000038
Raymond Hettinger20933e02010-09-01 06:58:25 +000039 The returned insertion point *i* partitions the array *a* into two halves so
40 that ``all(val <= x for val in a[lo:i])`` for the left side and
41 ``all(val > x for val in a[i:hi])`` for the right side.
Georg Brandl116aa622007-08-15 14:28:22 +000042
Georg Brandl0d8f0732009-04-05 22:20:44 +000043.. function:: insort_left(a, x, lo=0, hi=len(a))
Georg Brandl116aa622007-08-15 14:28:22 +000044
Georg Brandl0d8f0732009-04-05 22:20:44 +000045 Insert *x* in *a* in sorted order. This is equivalent to
Raymond Hettinger20933e02010-09-01 06:58:25 +000046 ``a.insert(bisect.bisect_left(a, x, lo, hi), x)`` assuming that *a* is
47 already sorted. Keep in mind that the O(log n) search is dominated by
48 the slow O(n) insertion step.
Georg Brandl116aa622007-08-15 14:28:22 +000049
Georg Brandl0d8f0732009-04-05 22:20:44 +000050.. function:: insort_right(a, x, lo=0, hi=len(a))
51 insort(a, x, lo=0, hi=len(a))
Georg Brandl116aa622007-08-15 14:28:22 +000052
Georg Brandl0d8f0732009-04-05 22:20:44 +000053 Similar to :func:`insort_left`, but inserting *x* in *a* after any existing
54 entries of *x*.
Georg Brandl116aa622007-08-15 14:28:22 +000055
Raymond Hettinger20933e02010-09-01 06:58:25 +000056.. seealso::
57
58 `SortedCollection recipe
59 <http://code.activestate.com/recipes/577197-sortedcollection/>`_ that uses
60 bisect to build a full-featured collection class with straight-forward search
61 methods and support for a key-function. The keys are precomputed to save
62 unnecessary calls to the key function during searches.
63
Georg Brandl116aa622007-08-15 14:28:22 +000064
Raymond Hettinger87c9d6c2010-08-07 07:36:55 +000065Searching Sorted Lists
66----------------------
67
Raymond Hettinger20933e02010-09-01 06:58:25 +000068The above :func:`bisect` functions are useful for finding insertion points but
69can be tricky or awkward to use for common searching tasks. The following five
Raymond Hettinger87c9d6c2010-08-07 07:36:55 +000070functions show how to transform them into the standard lookups for sorted
71lists::
72
Raymond Hettinger20933e02010-09-01 06:58:25 +000073 def index(a, x):
74 'Locate the leftmost value exactly equal to x'
75 i = bisect_left(a, x)
76 if i != len(a) and a[i] == x:
77 return i
78 raise ValueError
Raymond Hettinger87c9d6c2010-08-07 07:36:55 +000079
Raymond Hettinger20933e02010-09-01 06:58:25 +000080 def find_lt(a, x):
81 'Find rightmost value less than x'
82 i = bisect_left(a, x)
83 if i:
84 return a[i-1]
85 raise ValueError
86
87 def find_le(a, x):
88 'Find rightmost value less than or equal to x'
89 i = bisect_right(a, x)
90 if i:
91 return a[i-1]
92 raise ValueError
93
94 def find_gt(a, x):
95 'Find leftmost value greater than x'
96 i = bisect_right(a, x)
97 if i != len(a):
Raymond Hettinger87c9d6c2010-08-07 07:36:55 +000098 return a[i]
Raymond Hettinger20933e02010-09-01 06:58:25 +000099 raise ValueError
Raymond Hettinger87c9d6c2010-08-07 07:36:55 +0000100
Raymond Hettinger20933e02010-09-01 06:58:25 +0000101 def find_ge(a, x):
102 'Find leftmost item greater than or equal to x'
103 i = bisect_left(a, x)
104 if i != len(a):
Raymond Hettinger87c9d6c2010-08-07 07:36:55 +0000105 return a[i]
Raymond Hettinger20933e02010-09-01 06:58:25 +0000106 raise ValueError
Raymond Hettinger87c9d6c2010-08-07 07:36:55 +0000107
Raymond Hettinger87c9d6c2010-08-07 07:36:55 +0000108
109Other Examples
110--------------
Georg Brandl116aa622007-08-15 14:28:22 +0000111
112.. _bisect-example:
113
Raymond Hettinger20933e02010-09-01 06:58:25 +0000114The :func:`bisect` function can be useful for numeric table lookups. This
115example uses :func:`bisect` to look up a letter grade for an exam score (say)
116based on a set of ordered numeric breakpoints: 90 and up is an 'A', 80 to 89 is
117a 'B', and so on::
Georg Brandl116aa622007-08-15 14:28:22 +0000118
Raymond Hettinger20933e02010-09-01 06:58:25 +0000119 >>> def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
120 ... i = bisect(breakpoints, score)
121 ... return grades[i]
Georg Brandl116aa622007-08-15 14:28:22 +0000122 ...
Raymond Hettinger20933e02010-09-01 06:58:25 +0000123 >>> [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]
124 ['F', 'A', 'C', 'C', 'B', 'A', 'A']
Georg Brandl116aa622007-08-15 14:28:22 +0000125
Raymond Hettingere046d2a2009-06-11 22:01:24 +0000126Unlike the :func:`sorted` function, it does not make sense for the :func:`bisect`
127functions to have *key* or *reversed* arguments because that would lead to an
128inefficent design (successive calls to bisect functions would not "remember"
129all of the previous key lookups).
Georg Brandl116aa622007-08-15 14:28:22 +0000130
Raymond Hettingere046d2a2009-06-11 22:01:24 +0000131Instead, it is better to search a list of precomputed keys to find the index
132of the record in question::
133
134 >>> data = [('red', 5), ('blue', 1), ('yellow', 8), ('black', 0)]
Raymond Hettinger27352a52009-06-11 22:06:06 +0000135 >>> data.sort(key=lambda r: r[1])
136 >>> keys = [r[1] for r in data] # precomputed list of keys
Raymond Hettingere046d2a2009-06-11 22:01:24 +0000137 >>> data[bisect_left(keys, 0)]
138 ('black', 0)
139 >>> data[bisect_left(keys, 1)]
140 ('blue', 1)
141 >>> data[bisect_left(keys, 5)]
142 ('red', 5)
143 >>> data[bisect_left(keys, 8)]
144 ('yellow', 8)
Raymond Hettinger87c9d6c2010-08-07 07:36:55 +0000145