본문 바로가기
프로그래밍 문제/[Python] CheckIO

CheckIO - Nearest value

by UltraLowTemp-Physics 2020. 12. 2.
728x90

Problem: py.checkio.org/en/mission/nearest-value/ 

My solution

def nearest_value(values: set, one: int) -> int:
    # your code here
    n = 0
    while(not (one + n in values or one - n in values)):
        n = n + 1
    if one - n in values:
        return one - n 
    else:
        return one + n     


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!")

 

Good examples of solutions I think. 

def nearest_value(values: set, one: int) -> int:
    return min(values, key=lambda n: (abs(one - n), n))

 

def nearest_value(values: set, one: int) -> int:
    return min((abs(n-one), n) for n in values)[1]

 

def nearest_value(values: set, one: int) -> int:
    def distance(value): return abs(value - one), value > one
    return min(values, key=distance)

 

※ key, lambda function 

728x90

'프로그래밍 문제 > [Python] CheckIO' 카테고리의 다른 글

[CheckIO] Right to Left  (0) 2020.12.09
CheckIO - Even the last  (0) 2020.12.08
CheckIO-sum-numbers  (0) 2020.12.07
CheckIO - correct-sentence  (0) 2020.12.06
CheckIO - between-markers-simplified  (0) 2020.12.05

댓글