Last active
December 6, 2019 16:17
-
-
Save Syncrossus/c37494776f9ed641314e1359b16fe296 to your computer and use it in GitHub Desktop.
A simple function to carry out a dichotomy search (the optimal search for an item's index in a sorted list), because it does not exist in the standard library.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def dichotomy(ls, v, _i=0): | |
""" Dichotomy search, or the optimal search for an item's index | |
in a sorted list. | |
Arguments: | |
- (list) ls: the list in which to search, must be sorted for | |
this to work | |
- v: value to search for in the list, must be comparable to the | |
items in the list | |
- (int) _i: should not be used, is reserved for recursive purposes | |
Returns: | |
The index of v in ls if found, -1 if not. The value | |
returned is the first occurrence found, not guaranteed | |
to be the first in the list | |
""" | |
if ls == [] or ls is None: | |
return -1 | |
midvalue = len(ls) // 2 | |
if v < ls[midvalue]: | |
return dichotomy(ls[:midvalue], v, _i) | |
elif v > ls[midvalue]: | |
return dichotomy(ls[midvalue:], v, _i + midvalue) | |
else: | |
return _i + midvalue |
As it turns out, python sucks at recursivity so I recommend finding or writing your own iterative implementation.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code is released under the .