Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | :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 Hettinger | 20933e0 | 2010-09-01 06:58:25 +0000 | [diff] [blame] | 7 | .. sectionauthor:: Raymond Hettinger <python at rcn.com> |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 8 | .. example based on the PyModules FAQ entry by Aaron Watters <arw@pythonpros.com> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 9 | |
| 10 | This module provides support for maintaining a list in sorted order without |
| 11 | having to sort the list after each insertion. For long lists of items with |
| 12 | expensive comparison operations, this can be an improvement over the more common |
| 13 | approach. The module is called :mod:`bisect` because it uses a basic bisection |
| 14 | algorithm to do its work. The source code may be most useful as a working |
| 15 | example of the algorithm (the boundary conditions are already right!). |
| 16 | |
| 17 | The following functions are provided: |
| 18 | |
| 19 | |
Georg Brandl | 0d8f073 | 2009-04-05 22:20:44 +0000 | [diff] [blame] | 20 | .. function:: bisect_left(a, x, lo=0, hi=len(a)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 21 | |
Raymond Hettinger | 20933e0 | 2010-09-01 06:58:25 +0000 | [diff] [blame] | 22 | Locate the insertion point for *x* in *a* to maintain sorted order. |
Georg Brandl | 0d8f073 | 2009-04-05 22:20:44 +0000 | [diff] [blame] | 23 | 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 Hettinger | 20933e0 | 2010-09-01 06:58:25 +0000 | [diff] [blame] | 27 | parameter to ``list.insert()`` assuming that *a* is already sorted. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 28 | |
Raymond Hettinger | 20933e0 | 2010-09-01 06:58:25 +0000 | [diff] [blame] | 29 | 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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 32 | |
Georg Brandl | 0d8f073 | 2009-04-05 22:20:44 +0000 | [diff] [blame] | 33 | .. function:: bisect_right(a, x, lo=0, hi=len(a)) |
| 34 | bisect(a, x, lo=0, hi=len(a)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 35 | |
Georg Brandl | 0d8f073 | 2009-04-05 22:20:44 +0000 | [diff] [blame] | 36 | 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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 38 | |
Raymond Hettinger | 20933e0 | 2010-09-01 06:58:25 +0000 | [diff] [blame] | 39 | 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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 42 | |
Georg Brandl | 0d8f073 | 2009-04-05 22:20:44 +0000 | [diff] [blame] | 43 | .. function:: insort_left(a, x, lo=0, hi=len(a)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 44 | |
Georg Brandl | 0d8f073 | 2009-04-05 22:20:44 +0000 | [diff] [blame] | 45 | Insert *x* in *a* in sorted order. This is equivalent to |
Raymond Hettinger | 20933e0 | 2010-09-01 06:58:25 +0000 | [diff] [blame] | 46 | ``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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 49 | |
Georg Brandl | 0d8f073 | 2009-04-05 22:20:44 +0000 | [diff] [blame] | 50 | .. function:: insort_right(a, x, lo=0, hi=len(a)) |
| 51 | insort(a, x, lo=0, hi=len(a)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 52 | |
Georg Brandl | 0d8f073 | 2009-04-05 22:20:44 +0000 | [diff] [blame] | 53 | Similar to :func:`insort_left`, but inserting *x* in *a* after any existing |
| 54 | entries of *x*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 55 | |
Raymond Hettinger | 20933e0 | 2010-09-01 06:58:25 +0000 | [diff] [blame] | 56 | .. 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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 64 | |
Raymond Hettinger | 87c9d6c | 2010-08-07 07:36:55 +0000 | [diff] [blame] | 65 | Searching Sorted Lists |
| 66 | ---------------------- |
| 67 | |
Raymond Hettinger | 20933e0 | 2010-09-01 06:58:25 +0000 | [diff] [blame] | 68 | The above :func:`bisect` functions are useful for finding insertion points but |
| 69 | can be tricky or awkward to use for common searching tasks. The following five |
Raymond Hettinger | 87c9d6c | 2010-08-07 07:36:55 +0000 | [diff] [blame] | 70 | functions show how to transform them into the standard lookups for sorted |
| 71 | lists:: |
| 72 | |
Raymond Hettinger | 20933e0 | 2010-09-01 06:58:25 +0000 | [diff] [blame] | 73 | 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 Hettinger | 87c9d6c | 2010-08-07 07:36:55 +0000 | [diff] [blame] | 79 | |
Raymond Hettinger | 20933e0 | 2010-09-01 06:58:25 +0000 | [diff] [blame] | 80 | 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 Hettinger | 87c9d6c | 2010-08-07 07:36:55 +0000 | [diff] [blame] | 98 | return a[i] |
Raymond Hettinger | 20933e0 | 2010-09-01 06:58:25 +0000 | [diff] [blame] | 99 | raise ValueError |
Raymond Hettinger | 87c9d6c | 2010-08-07 07:36:55 +0000 | [diff] [blame] | 100 | |
Raymond Hettinger | 20933e0 | 2010-09-01 06:58:25 +0000 | [diff] [blame] | 101 | 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 Hettinger | 87c9d6c | 2010-08-07 07:36:55 +0000 | [diff] [blame] | 105 | return a[i] |
Raymond Hettinger | 20933e0 | 2010-09-01 06:58:25 +0000 | [diff] [blame] | 106 | raise ValueError |
Raymond Hettinger | 87c9d6c | 2010-08-07 07:36:55 +0000 | [diff] [blame] | 107 | |
Raymond Hettinger | 87c9d6c | 2010-08-07 07:36:55 +0000 | [diff] [blame] | 108 | |
| 109 | Other Examples |
| 110 | -------------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 111 | |
| 112 | .. _bisect-example: |
| 113 | |
Raymond Hettinger | 20933e0 | 2010-09-01 06:58:25 +0000 | [diff] [blame] | 114 | The :func:`bisect` function can be useful for numeric table lookups. This |
| 115 | example uses :func:`bisect` to look up a letter grade for an exam score (say) |
| 116 | based on a set of ordered numeric breakpoints: 90 and up is an 'A', 80 to 89 is |
| 117 | a 'B', and so on:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 118 | |
Raymond Hettinger | 20933e0 | 2010-09-01 06:58:25 +0000 | [diff] [blame] | 119 | >>> def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'): |
| 120 | ... i = bisect(breakpoints, score) |
| 121 | ... return grades[i] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 122 | ... |
Raymond Hettinger | 20933e0 | 2010-09-01 06:58:25 +0000 | [diff] [blame] | 123 | >>> [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]] |
| 124 | ['F', 'A', 'C', 'C', 'B', 'A', 'A'] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 125 | |
Raymond Hettinger | e046d2a | 2009-06-11 22:01:24 +0000 | [diff] [blame] | 126 | Unlike the :func:`sorted` function, it does not make sense for the :func:`bisect` |
| 127 | functions to have *key* or *reversed* arguments because that would lead to an |
| 128 | inefficent design (successive calls to bisect functions would not "remember" |
| 129 | all of the previous key lookups). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 130 | |
Raymond Hettinger | e046d2a | 2009-06-11 22:01:24 +0000 | [diff] [blame] | 131 | Instead, it is better to search a list of precomputed keys to find the index |
| 132 | of the record in question:: |
| 133 | |
| 134 | >>> data = [('red', 5), ('blue', 1), ('yellow', 8), ('black', 0)] |
Raymond Hettinger | 27352a5 | 2009-06-11 22:06:06 +0000 | [diff] [blame] | 135 | >>> data.sort(key=lambda r: r[1]) |
| 136 | >>> keys = [r[1] for r in data] # precomputed list of keys |
Raymond Hettinger | e046d2a | 2009-06-11 22:01:24 +0000 | [diff] [blame] | 137 | >>> 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 Hettinger | 87c9d6c | 2010-08-07 07:36:55 +0000 | [diff] [blame] | 145 | |