aboutsummaryrefslogtreecommitdiff
path: root/2021/10/puzzles.py
diff options
context:
space:
mode:
authorThomas Voss <thomasvoss@live.com> 2021-12-10 06:47:41 +0100
committerThomas Voss <thomasvoss@live.com> 2021-12-10 06:47:41 +0100
commit422cd4dd15e21c16b21dae9fe0145bdc9d3d2a30 (patch)
treedd156ac3d679c366590ea1c46e450965732e7afe /2021/10/puzzles.py
parent3b458cb1b362856045611820dbec763c179e8712 (diff)
Add typehints, use sorted() instead of .sort() and use reduce()
Diffstat (limited to '2021/10/puzzles.py')
-rw-r--r--2021/10/puzzles.py34
1 files changed, 13 insertions, 21 deletions
diff --git a/2021/10/puzzles.py b/2021/10/puzzles.py
index 0554d25..919638f 100644
--- a/2021/10/puzzles.py
+++ b/2021/10/puzzles.py
@@ -1,8 +1,13 @@
#!/usr/bin/env python3
# START PART 1
-from collections import Counter
-# END PART 1
+import collections
+from typing import Counter
+# END PART 1 START PART 2
+from functools import reduce
+# END PART 2
+
+OPEN = ("(", "[", "{", "<")
def main() -> None:
@@ -10,15 +15,15 @@ def main() -> None:
data = list(map(lambda l: l.strip(), f.readlines()))
# START PART 1
- counts = Counter()
+ counts: Counter[int] = Counter()
# END PART 1 START PART 2
- scores = []
+ scores: list[int] = []
# END PART 2
for line in data:
- stack = []
+ stack: list[int] = []
for char in line:
- if char in ("(", "[", "{", "<"):
+ if char in OPEN:
stack.append(char)
elif (stack.pop(), char) not in (("(", ")"), ("[", "]"), ("{", "}"), ("<", ">")):
# START PART 1
@@ -27,27 +32,14 @@ def main() -> None:
break
# START PART 2
else:
- score = 0
- for char in reversed(stack):
- score *= 5
- if char == "(":
- score += 1
- elif char == "[":
- score += 2
- elif char == "{":
- score += 3
- elif char == "<":
- score += 4
- scores.append(score)
+ scores.append(reduce(lambda acc, n: acc * 5 + OPEN.index(n) + 1, reversed(stack), 0))
# END PART 2
# START PART 1
print(counts[")"] * 3 + counts["]"] * 57 + counts["}"] * 1197 + counts[">"] * 25137)
# END PART 1 START PART 2
- scores.sort()
- print(scores[len(scores) // 2])
+ print(sorted(scores)[len(scores) // 2])
# END PART 2
-
if __name__ == "__main__":
main()