Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Nearest Value solution in Uncategorized category for Nearest Value by dnkomaroff
def nearest_value(values: set, one: int) -> int:
values = list(values)
values = sorted(values)
if one < values[0]:
return values[0]
elif one in values:
return one
elif one > values[len(values) - 1]:
return values[len(values) - 1]
else:
values.append(one)
values = sorted(values)
if values[values.index(one)] - values[values.index(one) - 1] < values[values.index(one) + 1] - values[values.index(one)]:
return values[values.index(one) - 1]
elif values[values.index(one)] - values[values.index(one) - 1] == values[values.index(one) + 1] - values[values.index(one)]:
x = []
x.append(values[values.index(one) - 1])
x.append(values[values.index(one) + 1])
return min(x)
else:
return values[values.index(one) + 1]
if __name__ == '__main__':
print("Example:")
print(nearest_value({4, 7, 10, 11, 12, 17}, 9))
# These "asserts" are used for self-checking and not for an auto-testing
assert nearest_value({4, 7, 10, 11, 12, 17}, 9) == 10
assert nearest_value({4, 7, 10, 11, 12, 17}, 8) == 7
assert nearest_value({4, 8, 10, 11, 12, 17}, 9) == 8
assert nearest_value({4, 9, 10, 11, 12, 17}, 9) == 9
assert nearest_value({4, 7, 10, 11, 12, 17}, 0) == 4
assert nearest_value({4, 7, 10, 11, 12, 17}, 100) == 17
assert nearest_value({5, 10, 8, 12, 89, 100}, 7) == 8
assert nearest_value({-1, 2, 3}, 0) == -1
print("Coding complete? Click 'Check' to earn cool rewards!")
April 1, 2021
Comments: