Created
October 26, 2017 22:21
-
-
Save nsfyn55/19ca7682017eeb851440a9f55977021c to your computer and use it in GitHub Desktop.
Find the closest integer in a list
This file contains hidden or 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 find_closest(t, vs): | |
vs.sort() | |
smallerest = None | |
for v in vs: | |
if not smallerest or (v < t and v > smallerest): | |
smallerest = v | |
vs.sort(reverse=True) | |
biggerest = None | |
for v in vs: | |
if not biggerest or (v > t and v < biggerest): | |
biggerest = v | |
s_distance = None | |
b_distance = None | |
if smallerest: | |
s_distance = t - smallerest | |
if biggerest: | |
b_distance = biggerest - t | |
if s_distance is None and b_distance is None: | |
raise RuntimeError() | |
if s_distance and b_distance is None: | |
return smallerest | |
if s_distance is None and b_distance: | |
return biggerest | |
if b_distance < s_distance: | |
return biggerest | |
return smallerest | |
t = 7 | |
vs = [1] | |
print find_closest(t, vs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment