diff options
| author | Simon Green <mail@simon.green> | 2025-08-31 21:45:29 +1000 |
|---|---|---|
| committer | Simon Green <mail@simon.green> | 2025-08-31 21:45:29 +1000 |
| commit | aae335bccca20a06aa5a45e5cafd50cca347cff3 (patch) | |
| tree | b6d624e56150a4349f2652abae9a70e1ee889323 /challenge-336/sgreen/python/ch-2.py | |
| parent | 923952d5af66503e9cd8d065a329f304796eab80 (diff) | |
| download | perlweeklychallenge-club-aae335bccca20a06aa5a45e5cafd50cca347cff3.tar.gz perlweeklychallenge-club-aae335bccca20a06aa5a45e5cafd50cca347cff3.tar.bz2 perlweeklychallenge-club-aae335bccca20a06aa5a45e5cafd50cca347cff3.zip | |
sgreen solutions to challenge 336
Diffstat (limited to 'challenge-336/sgreen/python/ch-2.py')
| -rwxr-xr-x | challenge-336/sgreen/python/ch-2.py | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/challenge-336/sgreen/python/ch-2.py b/challenge-336/sgreen/python/ch-2.py new file mode 100755 index 0000000000..ce381c551e --- /dev/null +++ b/challenge-336/sgreen/python/ch-2.py @@ -0,0 +1,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() |
