From 92cabbda8f5bcc838a47435f7670f8fce1398248 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Sun, 25 Dec 2022 11:24:28 +0100 Subject: [PATCH] 2022: d25: ex1: add solution --- 2022/d25/ex1/ex1.py | 50 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100755 2022/d25/ex1/ex1.py diff --git a/2022/d25/ex1/ex1.py b/2022/d25/ex1/ex1.py new file mode 100755 index 0000000..59686b9 --- /dev/null +++ b/2022/d25/ex1/ex1.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python + +import sys + + +def solve(input: list[str]) -> str: + def from_snafu(input: str) -> int: + res = 0 + for c in input: + if c == "=": + n = -2 + elif c == "-": + n = -1 + else: + n = int(c) + res = res * 5 + n + return res + + def to_snafu(input: int) -> str: + # Base case + if not input: + return "0" + + DIGITS = { + 2: "2", + 1: "1", + 0: "0", + -1: "-", + -2: "=", + } + + digits: list[int] = [] + while input: + input, d = divmod(input, 5) + if d not in DIGITS: + d -= 5 + input += 1 + digits.append(d) + return "".join(DIGITS[c] for c in reversed(digits)) + + return to_snafu(sum(map(from_snafu, input))) + + +def main() -> None: + input = sys.stdin.read().splitlines() + print(solve(input)) + + +if __name__ == "__main__": + main()