Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Test ``distance``for Nearest Value solution in Clear category for Nearest Value by seflaherty
#!/usr/bin/env checkio --domain=py run nearest-value
# Find the nearest value to the given one.
#
# You are given a list of values as set form and a value for which you need to find the nearest one.
#
# For example, we have the following set of numbers: 4, 7, 10, 11, 12, 17, and we need to find the nearest value to the number 9. If we sort this set in the ascending order, then to the left of number 9 will be number 7 and to the right - will be number 10. But 10 is closer than 7, which means that the correct answer is 10.
#
# A few clarifications:
#
# If 2 numbers are at the same distance, you need to choose the smallest one;The set of numbers is always non-empty, i.e. the size is >=1;The given value can be in this set, which means that it’s the answer;The set can contain both positive and negative numbers, but they are always integers;The set isn’t sorted and consists of unique numbers.Input:Two arguments. A list of values in the set form. The sought value is an int.
#
# Output:Int.
#
#
# END_DESC
import math
def nearest_value(values: set, one: int) -> int:
"""From a given set, return the integer closest in distance ta a separate
given integer. If given integer in set, return it, otherwise return lowest
closest value from the set.
:param values: A given set containing integers.
:param one: An integer to locate the nearest value to in the set.
:return: The nearest value in the set, lower value wins on tie.
"""
if one in values:
return one
else:
minimum = math.inf
for value in values:
distance = abs(value - one)
# At initalization, the distance of sequence item 1 from
# param ``one`` shall replace the default minimum of ``infinite``.
if distance < minimum:
minimum = abs(value - one)
# New minimum means replace the current ``final_value`` with the
# sequence item value
final_value = value
# There has been some looping… test that the already seen distance
# is the lower value one (e.g. for nearest to 8; 7 is less than 9)
elif distance == minimum:
final_value = min(value, final_value)
else:
continue
return final_value
if __name__ == '__main__':
print("Example:")
print(nearest_value({4, 7, 10, 11, 12, 17}, 9)) # ans: 10
print(nearest_value([0, -2], -1)) # ans: -2
# 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!")
Aug. 4, 2021
Comments: