Skip to content

Instantly share code, notes, and snippets.

@eviatarbach
Last active January 9, 2016 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eviatarbach/80e0accb7e8bf590ffc4 to your computer and use it in GitHub Desktop.
Save eviatarbach/80e0accb7e8bf590ffc4 to your computer and use it in GitHub Desktop.
A Python function that, given a lookup value, will find the index of the closest value in an equally-spaced list of numbers in constant time
def closest_index_in_range(lower, upper, step, value):
'''
Find the index of the closest value to `value` in the range
[lower, lower + step, ..., upper - step, upper] in constant time. `upper`
must be greater than `lower`. If `value` is outside the range, return the
corresponding boundary index (0 or the last index). When two values are
equally close, the index of the smaller is returned.
For example, `closest_index_in_range(-5, 5, 0.5, -4.8)` will return 0, since
-4.8 is closest to -5.
'''
if value >= upper:
return int((upper - lower)/step)
elif value < lower:
return 0
value = value - lower
upper = upper - lower
lower = 0
index = int(value//step + 1)
if step*index - value >= value - step*(index - 1):
index -= 1
return index
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment