[Python-checkins] r73368 - python/branches/release26-maint/Doc/library/bisect.rst

raymond.hettinger python-checkins at python.org
Fri Jun 12 00:04:49 CEST 2009


Author: raymond.hettinger
Date: Fri Jun 12 00:04:49 2009
New Revision: 73368

Log:
Add example of how to do key lookups with bisect().

Modified:
   python/branches/release26-maint/Doc/library/bisect.rst

Modified: python/branches/release26-maint/Doc/library/bisect.rst
==============================================================================
--- python/branches/release26-maint/Doc/library/bisect.rst	(original)
+++ python/branches/release26-maint/Doc/library/bisect.rst	Fri Jun 12 00:04:49 2009
@@ -85,4 +85,22 @@
    >>> map(grade, [33, 99, 77, 44, 12, 88])
    ['E', 'A', 'B', 'D', 'F', 'A']
 
+Unlike the :func:`sorted` function, it does not make sense for the :func:`bisect`
+functions to have *key* or *reversed* arguments because that would lead to an
+inefficent design (successive calls to bisect functions would not "remember"
+all of the previous key lookups).
 
+Instead, it is better to search a list of precomputed keys to find the index
+of the record in question::
+
+    >>> data = [('red', 5), ('blue', 1), ('yellow', 8), ('black', 0)]
+    >>> data.sort(key=lambda r: r[1])       # precomputed list of keys
+    >>> keys = [r[1] for r in data]
+    >>> data[bisect_left(keys, 0)]
+    ('black', 0)
+    >>> data[bisect_left(keys, 1)]
+    ('blue', 1)
+    >>> data[bisect_left(keys, 5)]
+    ('red', 5)
+    >>> data[bisect_left(keys, 8)]
+    ('yellow', 8)


More information about the Python-checkins mailing list