Skip to content

Instantly share code, notes, and snippets.

@wblondel
Created July 5, 2016 22:25
Show Gist options
  • Save wblondel/3392cd9cdc4c1890dd6b7ed5598db27e to your computer and use it in GitHub Desktop.
Save wblondel/3392cd9cdc4c1890dd6b7ed5598db27e to your computer and use it in GitHub Desktop.
Get number closest to a given value
from bisect import bisect_left
def takeClosest(myList, myNumber):
"""
Assumes myList is sorted. Returns closest value to myNumber.
If two numbers are equally close, return the smallest number.
"""
pos = bisect_left(myList, myNumber)
if pos == 0:
return myList[0]
if pos == len(myList):
return myList[-1]
before = myList[pos - 1]
after = myList[pos]
if after - myNumber < myNumber - before:
return after
else:
return before
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment