-
-
Notifications
You must be signed in to change notification settings - Fork 31.9k
Clarify that bisect(a, x, key=...) does not call key(x) #91966
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
>>> ns=[1,2,3,4,5]
>>> key_func = cmp_to_key(numeric_compare)
>>> bisect_right(ns, key_func(2), key=key_func)
2 Maybe this is worth documenting better? |
Here's an example of how it can be useful, by the way: >>> def isqrt(n):
... if n == 0 or n == 1:
... return n
... return bisect_left(range(n), True, key=lambda i: i*i>n) - 1 I'm searching for |
I agree that this can be fixed with documentation on the bisect functions -- I would never have deduced this usage from the error message or the examples. Thanks! |
I'll add another example in the final section showing the motivating use case. Will also amend the function specification to note that the key function is not called on the input value.
This example shows that for searching records you almost never have the full key ; that is what you're looking for. Instead you have a field value and want to find the matching record. |
The docs state To add to this, At the same time I understand the example use case, and the current design certainly works well there. I guess the counter-intuitivity is a necessary byproduct. |
… module (pythonGH-92602) (cherry picked from commit 63794db) Co-authored-by: Raymond Hettinger <[email protected]>
… module (pythonGH-92602) (cherry picked from commit 63794db) Co-authored-by: Raymond Hettinger <[email protected]>
The key functions generated by the functools.cmp_to_key function don't work with bisect.bisect_right or bisect.bisect_left, raising a TypeError with the message "TypeError: other argument must be K instance" when used.
Consider the following example derived from the Sorting HOWTO page (https://docs.python.org/3/howto/sorting.html#the-old-way-using-the-cmp-parameter)
The methods bisect.insort_left and bisect.insort_right functions do seem work correctly with these key functions:
Your environment
The text was updated successfully, but these errors were encountered: