Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Digit Stack by jcg
def pop(stack):
if stack:
return stack.pop()
else:
return 0
def push(stack, arg):
stack.append(int(arg))
def peek(stack):
if stack:
return stack[-1]
else:
return 0
def digit_stack(commands):
stack = []
s = 0
for cmd in commands:
analyzed_cmd = cmd.split(' ')
if len(analyzed_cmd) == 2:
push(stack, analyzed_cmd[1])
else:
if analyzed_cmd[0]=="POP":
s += pop(stack)
else:
s += peek(stack)
return s
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"
July 3, 2014