Object-oriented programming · 26 / 26 Exercise Medium

Stack as a class

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 EmptyStack and the class Stack with a private internal list and the methods push_item(x), pop_item() (returns and removes the last one) and top() (returns the last one without removing it). If the stack is empty, pop_item and top raise EmptyStack with the message empty stack.
  • Add __len__ (with len()) and __str__ (with the elements between brackets and separated by comma and space).
  • Read n and then n commands: push x (pushes the text x), pop, peek or size.
  • Show Popped: x, Top: x or Size: n depending on the command; if the exception occurs show Error: message. At the end show Stack: [...].
Input
5
push a
push b
peek
pop
size
Output
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