A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://mail.python.org/pipermail/python-dev/2009-June/089989.html below:

[Python-Dev] Adding key and reverse args to bisect

[Python-Dev] Adding key and reverse args to bisectRaymond Hettinger python at rcn.com
Thu Jun 11 23:33:03 CEST 2009
[David A. Barrett]
>I propose adding the key parameter
> to the bisect.bisect routines.  This
> would allow it to be used on lists with
> an ordering other than the one "natural"
> to the contained objects.

Algorithmically, the bisect routines are the wrong place to do key lookups.
If you do many calls to bisect(), each one will make multiple calls to the key
function, potentially repeating calls that were made on previous searches.
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])    # key function called exactly len(data) times
>>> 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)


Raymond
More information about the Python-Dev mailing list

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4