A Stack Class
Write a class Stack that holds items last in, first out:
push(item)adds an item on top.pop()removes and returns the top item; on an empty stack it raisesIndexError.peek()returns the top item without removing it; on an empty stack it raisesIndexError.len(stack)is the number of items, andbool(stack)isFalsefor an empty stack.
Understand the problem
Revise the behaviour and the special methods.
After push(1), push(2), push(3) and one pop(), what is the next pop()?
321
Last in, first out: the first pop() returns 3, the next returns 2. A stack is like a pile of plates: you only touch the top.
Which special method makes len(stack) work, and also makes an empty stack falsy in an if?
__len____size____count__
len() calls __len__. When a class has no __bool__ but has __len__, Python uses len(obj) != 0 for the truth value. One method gives both.
Write the solution
Write the class.
class Stack:
# Write your code here.
pass
Hint 1: a question to ask yourself
What built-in structure can hold the items and has an end that is cheap to add to and remove from?
Hint 2: the shape of the answer
Keep a list self._items. push is append, pop is the list pop() (which already raises IndexError when empty), peek is self._items[-1], __len__ is len(self._items).
Reflect
Solution
class Stack:
def __init__(self):
self._items = []
def push(self, item):
self._items.append(item)
def pop(self):
if not self._items:
raise IndexError("pop from empty stack")
return self._items.pop()
def peek(self):
if not self._items:
raise IndexError("peek at empty stack")
return self._items[-1]
def __len__(self):
return len(self._items)
What this tests: composition (the class has a list), a clean public interface, raising the right exception type, and __len__.
Why wrap a list instead of subclassing it: a Stack that inherits from list would also offer insert, sort and slicing, which break the idea of a stack. Wrapping exposes only the operations you intend.
Use the standard exceptions: IndexError for "nothing at that position", ValueError for "bad value", KeyError for "missing key". Callers already know how to handle them.
Why the list's end: append and pop() at the end are O(1). pop(0) at the front is O(n) because every item shifts. For a queue use collections.deque.
Cost: every operation is O(1).
What an interviewer might ask next: Use your stack to check whether brackets are balanced in "({[]})". (Push opening brackets, pop on closing ones, and compare.)
VISIBLE = 3
CASES = [
('s = Stack()\ns.push(1)\ns.push(2)\ns.push(3)\ns.pop()\nresult = s.pop()', 2, 'last in, first out'),
('s = Stack()\ns.push("a")\nresult = (s.peek(), len(s))', ('a', 1), 'peek does not remove'),
('result = error_of(Stack().pop)', 'IndexError', 'pop on an empty stack'),
('result = error_of(Stack().peek)', 'IndexError', 'peek on an empty stack'),
('s = Stack()\nresult = (len(s), bool(s))', (0, False), 'an empty stack is falsy'),
('s = Stack()\ns.push(0)\nresult = (len(s), bool(s))', (1, True), 'a stack with one item'),
('s = Stack()\nfor i in range(5):\n s.push(i)\nresult = [s.pop() for _ in range(5)]', [4, 3, 2, 1, 0], 'reverse order'),
('a = Stack()\nb = Stack()\na.push(1)\nresult = len(b)', 0, 'stacks are independent'),
('s = Stack()\ns.push(1)\ns.pop()\nresult = error_of(s.pop)', 'IndexError', 'empty again after popping'),
]