#577 · Stacks and queues · Beginner · 40 XP · about 8 min
A stack is a pile where the last item put on is the first one taken off. In Python a list makes a good stack: append puts an item on top and pop takes the top one off.
Write run_commands(commands) that starts with an empty stack, carries out each command in commands in order and returns a list of everything the commands report:
'PUSH x' puts the text x on top of the stack. It reports nothing.'POP' removes the top item and reports it, or reports 'Underflow' when the stack is empty.'PEEK' reports the top item without removing it, or 'Underflow' when the stack is empty.'EMPTY' reports 'yes' when the stack is empty and 'no' when it is not.'DISPLAY' reports every item from the top down, separated by single spaces, or 'Stack Empty' when there is nothing to show.Items are kept as text, so 'PUSH 7' pushes '7'.
run_commands(['PUSH 3', 'PUSH 8', 'PEEK', 'POP', 'DISPLAY']) # returns ['8', '8', '3'] run_commands(['POP', 'EMPTY', 'PUSH a', 'EMPTY']) # returns ['Underflow', 'yes', 'no'] run_commands(['PUSH 1', 'PUSH 2', 'PUSH 3', 'DISPLAY']) # returns ['3 2 1']
In the first example PEEK sees 8 on top and leaves it there, POP takes the 8 off, and DISPLAY shows the 3 that is left.
Items never contain spaces, and every command is written exactly as shown above.
First solves only, ranked by stars and then time.