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> |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 7 | .. 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] | 8 | |
| 9 | This module provides support for maintaining a list in sorted order without |
| 10 | having to sort the list after each insertion. For long lists of items with |
| 11 | expensive comparison operations, this can be an improvement over the more common |
| 12 | approach. The module is called :mod:`bisect` because it uses a basic bisection |
| 13 | algorithm to do its work. The source code may be most useful as a working |
| 14 | example of the algorithm (the boundary conditions are already right!). |
| 15 | |
| 16 | The following functions are provided: |
| 17 | |
| 18 | |
Georg Brandl | 0d8f073 | 2009-04-05 22:20:44 +0000 | [diff] [blame] | 19 | .. function:: bisect_left(a, x, lo=0, hi=len(a)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 20 | |
Georg Brandl | 0d8f073 | 2009-04-05 22:20:44 +0000 | [diff] [blame] | 21 | Locate the proper insertion point for *x* in *a* to maintain sorted order. |
| 22 | The parameters *lo* and *hi* may be used to specify a subset of the list |
| 23 | which should be considered; by default the entire list is used. If *x* is |
| 24 | already present in *a*, the insertion point will be before (to the left of) |
| 25 | any existing entries. The return value is suitable for use as the first |
| 26 | parameter to ``list.insert()``. This assumes that *a* is already sorted. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 27 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 28 | |
Georg Brandl | 0d8f073 | 2009-04-05 22:20:44 +0000 | [diff] [blame] | 29 | .. function:: bisect_right(a, x, lo=0, hi=len(a)) |
| 30 | bisect(a, x, lo=0, hi=len(a)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 31 | |
Georg Brandl | 0d8f073 | 2009-04-05 22:20:44 +0000 | [diff] [blame] | 32 | Similar to :func:`bisect_left`, but returns an insertion point which comes |
| 33 | after (to the right of) any existing entries of *x* in *a*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 34 | |
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 | .. function:: insort_left(a, x, lo=0, hi=len(a)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 37 | |
Georg Brandl | 0d8f073 | 2009-04-05 22:20:44 +0000 | [diff] [blame] | 38 | Insert *x* in *a* in sorted order. This is equivalent to |
| 39 | ``a.insert(bisect.bisect_left(a, x, lo, hi), x)``. This assumes that *a* is |
| 40 | already sorted. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 41 | |
Raymond Hettinger | 87c9d6c | 2010-08-07 07:36:55 +0000 | [diff] [blame^] | 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 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 45 | |
Georg Brandl | 0d8f073 | 2009-04-05 22:20:44 +0000 | [diff] [blame] | 46 | .. function:: insort_right(a, x, lo=0, hi=len(a)) |
| 47 | insort(a, x, lo=0, hi=len(a)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 48 | |
Georg Brandl | 0d8f073 | 2009-04-05 22:20:44 +0000 | [diff] [blame] | 49 | Similar to :func:`insort_left`, but inserting *x* in *a* after any existing |
| 50 | entries of *x*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 51 | |
Raymond Hettinger | 87c9d6c | 2010-08-07 07:36:55 +0000 | [diff] [blame^] | 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. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 54 | |
Raymond Hettinger | 87c9d6c | 2010-08-07 07:36:55 +0000 | [diff] [blame^] | 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 | -------------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 99 | |
| 100 | .. _bisect-example: |
| 101 | |
| 102 | The :func:`bisect` function is generally useful for categorizing numeric data. |
| 103 | This example uses :func:`bisect` to look up a letter grade for an exam total |
| 104 | (say) based on a set of ordered numeric breakpoints: 85 and up is an 'A', 75..84 |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 105 | is a 'B', etc. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 106 | |
| 107 | >>> grades = "FEDCBA" |
| 108 | >>> breakpoints = [30, 44, 66, 75, 85] |
| 109 | >>> from bisect import bisect |
| 110 | >>> def grade(total): |
| 111 | ... return grades[bisect(breakpoints, total)] |
| 112 | ... |
| 113 | >>> grade(66) |
| 114 | 'C' |
| 115 | >>> map(grade, [33, 99, 77, 44, 12, 88]) |
| 116 | ['E', 'A', 'B', 'D', 'F', 'A'] |
| 117 | |
Raymond Hettinger | e046d2a | 2009-06-11 22:01:24 +0000 | [diff] [blame] | 118 | Unlike the :func:`sorted` function, it does not make sense for the :func:`bisect` |
| 119 | functions to have *key* or *reversed* arguments because that would lead to an |
| 120 | inefficent design (successive calls to bisect functions would not "remember" |
| 121 | all of the previous key lookups). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 122 | |
Raymond Hettinger | e046d2a | 2009-06-11 22:01:24 +0000 | [diff] [blame] | 123 | Instead, it is better to search a list of precomputed keys to find the index |
| 124 | of the record in question:: |
| 125 | |
| 126 | >>> data = [('red', 5), ('blue', 1), ('yellow', 8), ('black', 0)] |
Raymond Hettinger | 27352a5 | 2009-06-11 22:06:06 +0000 | [diff] [blame] | 127 | >>> data.sort(key=lambda r: r[1]) |
| 128 | >>> keys = [r[1] for r in data] # precomputed list of keys |
Raymond Hettinger | e046d2a | 2009-06-11 22:01:24 +0000 | [diff] [blame] | 129 | >>> data[bisect_left(keys, 0)] |
| 130 | ('black', 0) |
| 131 | >>> data[bisect_left(keys, 1)] |
| 132 | ('blue', 1) |
| 133 | >>> data[bisect_left(keys, 5)] |
| 134 | ('red', 5) |
| 135 | >>> data[bisect_left(keys, 8)] |
| 136 | ('yellow', 8) |
Raymond Hettinger | 87c9d6c | 2010-08-07 07:36:55 +0000 | [diff] [blame^] | 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. |