Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Beginner's solution solution in Clear category for Nearest Value by Selindian
def nearest_value(values: set, one: int) -> int:
# your code here
if one in values: return one # If int exists in set return int
nearest = "unset" # Define variable nearest
for elem in values: # Loop over all elements of the set
if nearest == "unset": # In first loop:
nearest = elem # set nearest to value of current element
if abs(one - nearest) > abs(one - elem): # If absolute diff of (one - nearest) > (one - elem)
nearest = elem # nearest will get value of elem
elif abs(one - nearest) == abs(one - elem): # if absolute diff of (one - nearest) == (one - elem)
if nearest > elem: # if nearest > elem (we need to find the samller number of equal diffs)
nearest = elem # nearest will get value of elem
return nearest
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({5}, 5) == 5
assert nearest_value({5}, 7) == 5
print("Coding complete? Click 'Check' to earn cool rewards!")
Feb. 21, 2022
Comments: