blob: ce381c551e948c1a12ebd6ad65ac054f0b99fb10 (
plain)
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
|
#!/usr/bin/env python3
import re
import sys
def final_score(scores: list[str]) -> int:
score_stack = []
for score in scores:
if score == "C":
# Clear the previous score
if not score_stack:
raise ValueError("No scores to remove for 'C' operation")
score_stack.pop()
elif score == "D":
# Double the previous score
if not score_stack:
raise ValueError("No scores to double for 'D' operation")
score_stack.append(2 * score_stack[-1])
elif score == "+":
# Sum the previous two scores
if len(score_stack) < 2:
raise ValueError("Not enough scores to sum for '+' operation")
score_stack.append(score_stack[-1] + score_stack[-2])
elif re.match(r"^-?\d+$", score):
# It's a valid integer score
score_stack.append(int(score))
else:
# We don't know what score this is
raise ValueError(f"Invalid score entry: {score}")
return sum(score_stack)
def main():
result = final_score(sys.argv[1:])
print(result)
if __name__ == '__main__':
main()
|