|
| 1 | +import itertools |
1 | 2 | import math |
2 | 3 | from pathlib import Path |
3 | 4 |
|
@@ -27,34 +28,30 @@ def part_1(input: Path) -> int: |
27 | 28 |
|
28 | 29 |
|
29 | 30 | def part_2(input: Path) -> int: |
30 | | - text = [[c for c in line] for line in input.read_text().splitlines()] |
31 | | - len_longest_line = max(len(line) for line in text) |
32 | | - text = [line + [" "] * (len_longest_line - len(line)) for line in text] |
| 31 | + text = transpose_text(input.read_text()) |
33 | 32 |
|
34 | 33 | answers = [] |
35 | 34 | this_problem_numbers = [] |
36 | | - for col in range(len(text[0]) - 1, -1, -1): |
37 | | - number: int | None = None |
38 | | - operator: str | None = None |
39 | | - for row in range(len(text)): |
40 | | - char = text[row][col] |
41 | | - if char.isnumeric(): |
42 | | - if number is None: |
43 | | - number = int(char) |
44 | | - else: |
45 | | - number = 10 * number + int(char) |
46 | | - elif char != " ": |
47 | | - operator = char |
48 | | - if number is not None: |
49 | | - this_problem_numbers.append(number) |
50 | | - if operator is not None: |
51 | | - match operator: |
| 35 | + for line in reversed(text.splitlines()): |
| 36 | + if not line: |
| 37 | + continue |
| 38 | + if line.endswith("+") or line.endswith("*"): |
| 39 | + this_problem_numbers.append(int(line[:-1])) |
| 40 | + match line[-1]: |
52 | 41 | case "+": |
53 | 42 | answers.append(sum(this_problem_numbers)) |
54 | 43 | case "*": |
55 | 44 | answers.append(math.prod(this_problem_numbers)) |
56 | 45 | case _: |
57 | | - raise ValueError(f"Invalid operator: {operator}") |
| 46 | + raise ValueError(f"Invalid operator: {line[-1]}") |
58 | 47 | this_problem_numbers = [] |
| 48 | + else: |
| 49 | + this_problem_numbers.append(int(line)) |
59 | 50 |
|
60 | 51 | return sum(answers) |
| 52 | + |
| 53 | + |
| 54 | +def transpose_text(s: str) -> str: |
| 55 | + lines = s.splitlines() |
| 56 | + transposed_lines = itertools.zip_longest(*lines, fillvalue=" ") |
| 57 | + return "\n".join("".join(line).rstrip() for line in transposed_lines) |
0 commit comments