Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Second solution in Clear category for Digit Stack by tom-tom
def digit_stack(commands):
stack = []
oper = {'PUSH': lambda n: stack.append(int(n)),
'POP': lambda w: stack.pop() if stack else 0,
'PEEK': lambda w: stack[-1] if stack else 0}
return sum(int(oper[command.split()[0]](command.split()[-1]) or 0) for command in commands)
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert digit_stack(["PUSH 3", "POP", "POP", "PUSH 4", "PEEK",
"PUSH 9", "PUSH 0", "PEEK", "POP", "PUSH 1", "PEEK"]) == 8, "Example"
assert digit_stack(["POP", "POP"]) == 0, "pop, pop, zero"
assert digit_stack(["PUSH 9", "PUSH 9", "POP"]) == 9, "Push the button"
assert digit_stack([]) == 0, "Nothing"
Feb. 16, 2017