Edexcel International Advanced Level Computer Science, point 8.2.5
A stack (4.3.1) follows last in, first out. Here you implement it in code using a fixed-length list (a list whose size is set when created and doesn't change), with a pointer to the top. Check the PLS for the exact conventions the exam uses.
The idea
- The list has a capacity (its fixed length).
topholds the index of the top item.-1means empty.- Push moves
topup by one and stores the item there. - Pop reads the item at
topand movestopdown by one. (The old value is left in place but is ignored.)
a. Create
CAPACITY = 5
stack = [None] * CAPACITY # fixed-length list
top = -1 # empty
d. IsEmpty, e. IsFull, f. Size
def is_empty(top):
return top == -1
def is_full(top):
return top == CAPACITY - 1
def size(top):
return top + 1
- Empty when
top == -1. - Full when
topis the last index (capacity - 1). - Size (number of items) is
top + 1.
b. Push
def push(stack, top, item):
if is_full(top):
print("Stack full")
return top # unchanged
top = top + 1
stack[top] = item
return top
c. Pop
def pop(stack, top):
if is_empty(top):
print("Stack empty")
return None, top
item = stack[top]
top = top - 1
return item, top
Check for full before push and empty before pop, so that you avoid overflow and underflow.
Using the functions
stack = [None] * CAPACITY
top = -1
top = push(stack, top, 5)
top = push(stack, top, 9)
top = push(stack, top, 14)
item, top = pop(stack, top) # item is 14
print(item, size(top)) # 14 2
A class version (neater)
Wrapping the list and pointer in a class keeps them together:
class Stack:
def __init__(self, capacity):
self.items = [None] * capacity
self.top = -1
def is_empty(self):
return self.top == -1
def is_full(self):
return self.top == len(self.items) - 1
def size(self):
return self.top + 1
def push(self, item):
if self.is_full():
raise OverflowError("stack is full")
self.top += 1
self.items[self.top] = item
def pop(self):
if self.is_empty():
raise IndexError("stack is empty")
item = self.items[self.top]
self.top -= 1
return item
Hand trace (capacity 3)
| Operation | top |
List contents | Notes |
|---|---|---|---|
| Create | -1 | [None, None, None] |
empty |
| push(7) | 0 | [7, None, None] |
|
| push(3) | 1 | [7, 3, None] |
|
| push(8) | 2 | [7, 3, 8] |
full |
| push(1) | 2 | [7, 3, 8] |
rejected: overflow |
| pop() | 1 | [7, 3, 8] |
returns 8 (the 8 stays in the list but is ignored) |
| pop() | 0 | [7, 3, 8] |
returns 3 |
| size() | 0 | 1 |
Other ways to make a stack in Python
# 1. An ordinary list (a dynamic stack, with no fixed size)
pile = []
pile.append("a") # push
pile.append("b")
print(pile.pop()) # pop -> b
# 2. LifoQueue from the queue module
from queue import LifoQueue
q = LifoQueue(maxsize=3) # a stack with room for 3
q.put("x") # push
q.put("y")
print(q.get()) # pop -> y
print(q.empty(), q.full()) # False False
The specification asks for the fixed-length list version because it makes you handle the pointer and the full and empty checks yourself: an ordinary list never becomes full, and LifoQueue does the checking for you.
Worked example: denary to binary with a stack
Dividing by 2 gives the bits from right to left, so they are pushed as they are found and popped to read them left to right.
def to_binary(n):
s = Stack(16) # room for 16 bits
if n == 0:
return "0"
while n > 0:
s.push(n % 2) # push each remainder
n = n // 2
bits = ""
while not s.is_empty(): # pop them back off
bits = bits + str(s.pop())
return bits
print(to_binary(13)) # 1101
For 13: the remainders are 1, 0, 1, 1 (13, 6, 3, 1 divided by 2), pushed in that order. Popping gives them back in reverse, 1, 1, 0, 1, which is 1101.
Exam tip: know what top == -1 means, how to work out full (top == capacity - 1) and size (top + 1), and check before pushing and popping. When tracing, show the pointer and the list, and remember that popped values aren't erased, only ignored.
Check yourself
What does top = -1 mean?
The stack is empty.
How do you test whether a stack in a list of length 10 is full?
top == 9 (the last index, which is capacity − 1).
What happens to the pointer when you push and when you pop?
Push increases it by one (after checking it isn't full). Pop decreases it by one (after checking it isn't empty).
What is the size of a stack whose top pointer is 4?
5 items (top + 1).