aboutsummaryrefslogtreecommitdiff
path: root/challenge-336/packy-anderson/python/ch-2.py
diff options
context:
space:
mode:
authorPacky Anderson <packy@cpan.org>2025-08-26 23:46:56 -0400
committerPacky Anderson <packy@cpan.org>2025-08-26 23:46:56 -0400
commitf71789d6afb418fc6351912afd6da3a6b40766ca (patch)
treed950d9cf8db4d21ea60d912bb74dffa1ddb6765c /challenge-336/packy-anderson/python/ch-2.py
parent778a877423d75f6299c57bb75c3edffd2f304e84 (diff)
downloadperlweeklychallenge-club-f71789d6afb418fc6351912afd6da3a6b40766ca.tar.gz
perlweeklychallenge-club-f71789d6afb418fc6351912afd6da3a6b40766ca.tar.bz2
perlweeklychallenge-club-f71789d6afb418fc6351912afd6da3a6b40766ca.zip
Challenge 336 solutions by Packy Anderson
* Raku that maybe looks like Raku, but mostly like Perl * Perl * Python that definitely looks like Perl * Elixir that is starting to look like Elixir 1 blog post
Diffstat (limited to 'challenge-336/packy-anderson/python/ch-2.py')
-rwxr-xr-xchallenge-336/packy-anderson/python/ch-2.py53
1 files changed, 53 insertions, 0 deletions
diff --git a/challenge-336/packy-anderson/python/ch-2.py b/challenge-336/packy-anderson/python/ch-2.py
new file mode 100755
index 0000000000..4d43d4745b
--- /dev/null
+++ b/challenge-336/packy-anderson/python/ch-2.py
@@ -0,0 +1,53 @@
+#!/usr/bin/env python
+
+def final_score(scores):
+ stack = []
+ rounds = ""
+ count = 0
+ for action in scores:
+ if stack: previous = stack[-1]
+ match action:
+ case '+':
+ stack.append( stack[-1] + stack[-2] )
+ case 'C':
+ stack.pop()
+ case 'D':
+ stack.append( stack[-1] * 2 )
+ case _:
+ stack.append( int(action) )
+ count += 1
+ rounds += "Round {:2d}: ".format(count)
+ rounds += " + ".join([
+ f'({n})' if n < 0 else f'{n}' for n in stack
+ ])
+ if action == "+":
+ rounds += " (sum of previous two scores)"
+ if action == "D":
+ rounds += f" (double the previous score {previous})"
+ if action == "C":
+ rounds += f" (invalidate the previous score {previous})"
+ rounds += "\n"
+ total = sum(stack)
+ rounds += f"\nTotal Scores: {total}"
+ return (total, rounds)
+
+def solution(scores):
+ score_list = ', '.join([ f'"{s}"' for s in scores ])
+ print(f'Input: @scores = ({score_list})')
+ output, rounds = final_score(scores)
+ print(f'Output: {output}\n\n{rounds}')
+
+print('Example 1:')
+solution(["5","2","C","D","+"])
+
+print('\nExample 2:')
+solution(["5","-2","4","C","D","9","+","+"])
+
+print('\nExample 3:')
+solution(["7","D","D","C","+","3"])
+
+print('\nExample 4:')
+solution(["-5","-10","+","D","C","+"])
+
+print('\nExample 5:')
+solution(["3","6","+","D","C","8","+","D","-2","C","+"])