-
Notifications
You must be signed in to change notification settings - Fork 0
/
AoC2023_01.py
98 lines (78 loc) 路 2.05 KB
/
AoC2023_01.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#! /usr/bin/env python3
#
# Advent of Code 2023 Day 1
#
import sys
from typing import Callable
from aoc.common import InputData
from aoc.common import SolutionBase
from aoc.common import aoc_samples
Input = InputData
Output1 = int
Output2 = int
TEST1 = """\
1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet
"""
TEST2 = """\
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen
"""
class Solution(SolutionBase[Input, Output1, Output2]):
def parse_input(self, input_data: InputData) -> Input:
return input_data
def _solve(self, input: InputData, f: Callable[[str], list[int]]) -> int:
return sum(
map(lambda digits: digits[0] * 10 + digits[-1], map(f, input))
)
def part_1(self, input: InputData) -> Output1:
def get_digits(line: str) -> list[int]:
return [int(c) for c in line if c.isdigit()]
return self._solve(input, get_digits)
def part_2(self, input: InputData) -> Output2:
def get_digits(line: str) -> list[int]:
nums = [
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
]
def find_digit(s: str) -> int | None:
if s[0].isdigit():
return int(s[0])
else:
for j, num in enumerate(nums):
if s.startswith(num):
return j + 1
return None
return [
x
for x in map(lambda i: find_digit(line[i:]), range(len(line)))
if x is not None
]
return self._solve(input, get_digits)
@aoc_samples(
(
("part_1", TEST1, 142),
("part_2", TEST2, 281),
)
)
def samples(self) -> None:
pass
solution = Solution(2023, 1)
def main() -> None:
solution.run(sys.argv)
if __name__ == "__main__":
main()