Objective
A stack (last in, first out) is a good example of an abstract data type: the class hides how it stores the elements and offers only the allowed operations.
Instructions
- Define the exception
EmptyStackand the classStackwith a private internal list and the methodspush_item(x),pop_item()(returns and removes the last one) andtop()(returns the last one without removing it). If the stack is empty,pop_itemandtopraiseEmptyStackwith the messageempty stack. - Add
__len__(withlen()) and__str__(with the elements between brackets and separated by comma and space). - Read
nand thenncommands:push x(pushes the textx),pop,peekorsize. - Show
Popped: x,Top: xorSize: ndepending on the command; if the exception occurs showError: message. At the end showStack: [...].
5
push a
push b
peek
pop
size
Top: b
Popped: b
Size: 1
Stack: [a]
Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.
Start exercise