Skip to content

Commit b8fdb90

Browse files
Viliam PucikViliam Pucik
Viliam Pucik
authored and
Viliam Pucik
committed
optimized
1 parent 4ea875f commit b8fdb90

File tree

1 file changed

+13
-18
lines changed

1 file changed

+13
-18
lines changed

2023/01.py

+13-18
Original file line numberDiff line numberDiff line change
@@ -3,24 +3,19 @@
33

44
lines = open(0).read().splitlines()
55
# fmt:off
6-
print(sum(
7-
x[0] * 10 + x[-1]
8-
for line in lines
9-
for x in [[int(i) for i in line if i.isdigit()]]
10-
))
6+
digits = {"1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9}
7+
# fmt:on
8+
keys = "|".join(digits.keys())
119

12-
# Alternative and probably faster solution
13-
# print(sum(
14-
# next(int(i) for i in line if i.isdigit()) * 10 +
15-
# next(int(i) for i in reversed(line) if i.isdigit())
16-
# for line in lines
17-
# ))
1810

19-
digits = {"1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9}
20-
r = re.compile(rf"(?=({ '|'.join(digits.keys()) }))")
11+
def solve(lines, r_first, r_last):
12+
return sum(
13+
# fmt:off
14+
digits[r_first.search(line)[1]] * 10 + digits[r_last.search(line)[1]]
15+
for line in lines
16+
# fmt:on
17+
)
18+
2119

22-
print(sum(
23-
digits[x[0]] * 10 + digits[x[-1]]
24-
for line in lines
25-
for x in [r.findall(line)]
26-
))
20+
print(solve(lines, re.compile(r"(\d)"), re.compile(r".*(\d)")))
21+
print(solve(lines, re.compile(rf"({keys})"), re.compile(rf".*({keys})")))

0 commit comments

Comments
 (0)