From 173c32d6f21b793f1292e1402d6ba0f8afbe7991 Mon Sep 17 00:00:00 2001 From: Divlo Date: Sun, 1 May 2022 19:11:11 +0200 Subject: [PATCH] feat(solutions): add `find-closest-number/python/linear` --- .../solutions/python/linear/README.md | 3 +++ .../solutions/python/linear/solution.py | 21 +++++++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 challenges/find-closest-number/solutions/python/linear/README.md create mode 100644 challenges/find-closest-number/solutions/python/linear/solution.py diff --git a/challenges/find-closest-number/solutions/python/linear/README.md b/challenges/find-closest-number/solutions/python/linear/README.md new file mode 100644 index 0000000..45c7a28 --- /dev/null +++ b/challenges/find-closest-number/solutions/python/linear/README.md @@ -0,0 +1,3 @@ +# find-closest-number/python/linear + +Created by [@Divlo](https://github.com/Divlo) on 1 May 2022. diff --git a/challenges/find-closest-number/solutions/python/linear/solution.py b/challenges/find-closest-number/solutions/python/linear/solution.py new file mode 100644 index 0000000..0e6d8f6 --- /dev/null +++ b/challenges/find-closest-number/solutions/python/linear/solution.py @@ -0,0 +1,21 @@ +import sys + + +def find_closest_number(integers: list[int], value: int) -> int: + """ + From list of integers, get number closest to a given value + """ + current = integers[0] + for number in integers: + if abs(number - value) < abs(current - value): + current = number + return current + + +numbers: list[int] = [] +for value in sys.stdin: + numbers.append(int(value.rstrip('\n'))) + +given_number = numbers[0] +numbers = numbers[2:] +print(find_closest_number(numbers, given_number))