From f71789d6afb418fc6351912afd6da3a6b40766ca Mon Sep 17 00:00:00 2001 From: Packy Anderson Date: Tue, 26 Aug 2025 23:46:56 -0400 Subject: 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 --- challenge-336/packy-anderson/python/ch-2.py | 53 +++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100755 challenge-336/packy-anderson/python/ch-2.py (limited to 'challenge-336/packy-anderson/python/ch-2.py') 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","+"]) -- cgit