|
| 1 | +""" |
| 2 | + # Nearest Value |
| 3 | +
|
| 4 | + ## Find the nearest value to the given one. |
| 5 | + ## You are given a list of values as set form and a value for which you need to find the nearest one. |
| 6 | + ## For example, we have the following set of numbers: 4, 7, 10, 11, 12, 17, |
| 7 | + ## and we need to find the nearest value to the number 9. |
| 8 | + ## If we sort this set in the ascending order, then to the left of number 9 will be number 7 and |
| 9 | + ## to the right - will be number 10. |
| 10 | + ## But 10 is closer than 7, which means that the correct answer is 10. |
| 11 | +
|
| 12 | + ## A few clarifications: |
| 13 | + ## -> If 2 numbers are at the same distance, you need to choose the smallest one; |
| 14 | + ## -> The set of numbers is always non-empty, i.e. the size is >=1; |
| 15 | + ## -> The given value can be in this set, which means that it’s the answer; |
| 16 | + ## -> The set can contain both positive and negative numbers, but they are always integers; |
| 17 | + ## -> The set isn’t sorted and consists of unique numbers. |
| 18 | +
|
| 19 | + - Input: Two arguments. A list of values in the set form. The sought value is an int. |
| 20 | +
|
| 21 | + - Output: Int. |
| 22 | +""" |
| 23 | + |
| 24 | + |
| 25 | +def nearest_value(values: set, one: int) -> int: |
| 26 | + if one in values: |
| 27 | + return one |
| 28 | + |
| 29 | + minor_distance = 1 |
| 30 | + |
| 31 | + while True: |
| 32 | + if (one - minor_distance) in values: |
| 33 | + return (one - minor_distance) |
| 34 | + elif (one + minor_distance) in values: |
| 35 | + return (one + minor_distance) |
| 36 | + else: |
| 37 | + minor_distance += 1 |
| 38 | + |
| 39 | + |
| 40 | +# These "asserts" are used for self-checking and not for an auto-testing |
| 41 | +assert nearest_value({4, 7, 10, 11, 12, 17}, 9) == 10 |
| 42 | +assert nearest_value({4, 7, 10, 11, 12, 17}, 8) == 7 |
| 43 | +assert nearest_value({4, 8, 10, 11, 12, 17}, 9) == 8 |
| 44 | +assert nearest_value({4, 9, 10, 11, 12, 17}, 9) == 9 |
| 45 | +assert nearest_value({4, 7, 10, 11, 12, 17}, 0) == 4 |
| 46 | +assert nearest_value({4, 7, 10, 11, 12, 17}, 100) == 17 |
| 47 | +assert nearest_value({5, 10, 8, 12, 89, 100}, 7) == 8 |
| 48 | +assert nearest_value({-1, 2, 3}, 0) == -1 |
0 commit comments