Sub topic 7
Two implementations of the same stack
This chapter assumes you know the stack specification from the previous chapter: push, pop, peek, and is_empty, with pop and peek raising IndexError on an empty stack. You should also be comfortable with Python classes, lists, and object references.
One promise, two representations
An abstract data type (ADT) fixes behavior. It does not fix storage. So one specification can be met by several classes that store their items differently. Here we build two. ListStack keeps items in a Python list. LinkedStack keeps them in a chain of nodes.
The interface
This is the same interface as before, with the docstrings shortened.
from abc import ABC, abstractmethod
class Stack(ABC):
"""A last-in, first-out collection.
pop() and peek() raise IndexError on an empty stack.
"""
@abstractmethod
def push(self, item): ...
@abstractmethod
def pop(self): ...
@abstractmethod
def peek(self): ...
@abstractmethod
def is_empty(self): ...Implementation 1: a list
ListStack treats the end of a Python list as the top of the stack. append and pop both work at that end.
class ListStack(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 is_empty(self):
return not self._itemsThe empty check comes first. Without it, the list would still raise IndexError, but only because of how Python lists behave. The explicit check ties the error to the specification, so it holds even if the representation changes.
Implementation 2: linked nodes
LinkedStack stores each item in a _Node that points to the node below it. The head node is the top. Pushing makes a new head. Popping moves the head to the next node.
class _Node:
def __init__(self, value, next_node):
self.value = value
self.next = next_node
class LinkedStack(Stack):
def __init__(self):
self._head = None
def push(self, item):
self._head = _Node(item, self._head)
def pop(self):
if self._head is None:
raise IndexError("pop from empty stack")
value = self._head.value
self._head = self._head.next
return value
def peek(self):
if self._head is None:
raise IndexError("peek at empty stack")
return self._head.value
def is_empty(self):
return self._head is NoneThe two classes share no storage code. The only things they have in common are the method names, the behavior, and the error case.
Same behavior, different internals
A client that uses only the interface cannot tell them apart.
def reverse(items, stack):
for x in items:
stack.push(x)
result = []
while not stack.is_empty():
result.append(stack.pop())
return result
for make_stack in (ListStack, LinkedStack):
print(reverse([1, 2, 3], make_stack()))
# [3, 2, 1]
# [3, 2, 1]reverse receives a stack object and calls only push, pop, and is_empty. It never touches _items or _head. That is why you can swap implementations without editing it.
Common errors
- Reading the representation from outside. A client that uses
stack._itemsworks withListStackand breaks withLinkedStack. Treat names that start with an underscore as private. - Letting behavior drift. If
LinkedStack.popreturnedNoneon an empty stack, clients that rely onIndexErrorwould fail only for that class. Every implementation must keep every promise in the specification. - Mixing up the layers. The list and the node chain are data structures. The stack is the ADT. Several implementations can meet one ADT.
Exercise
You add a size() method to the Stack specification. What must you change in ListStack and LinkedStack, and what must you change in reverse?
Show answer
Add size() to both classes. ListStack can return len(self._items). LinkedStack can count nodes by walking the chain, or keep a counter that push and pop update. reverse needs no change, because it only uses operations it already had, and adding an operation does not alter the behavior it depends on.