Show contents
Chapter 6 of 7 · 25 min
Project: a support ticket manager
By the end of this chapter, you'll be able to
- Choose a suitable data structure for each need of a program
- Combine a heap, a dictionary, a set and a stack in a single class
- Keep several structures consistent with each other
- Test a program on a complete scenario
The requirements
| Need | Structure | Why |
|---|---|---|
| Handle the most serious ticket first, and for equal severity the oldest | heapq heap of (severity, number) tuples | remove the top priority in O(log n) |
| Find a ticket by its number | dictionary {number: ticket} | O(1) access |
| Know how many different customers wrote in | set of customers | duplicates removed automatically |
| Undo the last closure | stack of closed tickets | the last one closed is the first one reopened |
Severity goes from 1 (danger) to 3 (simple request). The ticket number increases with each new ticket: it also serves as the order of arrival.
Step 1: create and find tickets
import heapq
class Support:
def __init__(self):
self.tickets = {}
self.to_handle = []
self.customers = set()
self.closed = []
self.next_number = 1
def open(self, customer, subject, severity):
number = self.next_number
self.next_number += 1
self.tickets[number] = {"customer": customer, "subject": subject, "severity": severity, "state": "open"}
heapq.heappush(self.to_handle, (severity, number))
self.customers.add(customer)
return number
support = Support()
support.open("Awa", "The panel no longer charges", 2)
support.open("Kofi", "Change my address", 3)
n = support.open("Lina", "The battery is hot and smoking", 1)
support.open("Awa", "Duplicate invoice", 3)
print(len(support.tickets), "tickets,", len(support.customers), "customers")
print(support.tickets[n])
4 tickets, 3 customers
{'customer': 'Lina', 'subject': 'The battery is hot and smoking', 'severity': 1, 'state': 'open'}
Step 2: handle, close and undo
Handling a ticket means taking the top priority out of the heap, marking it "closed" and recording it on the stack. Undoing means popping the last closed ticket and putting it back in the heap.
import heapq
class Support:
def __init__(self):
self.tickets, self.to_handle, self.customers, self.closed, self.next_number = {}, [], set(), [], 1
def open(self, customer, subject, severity):
number = self.next_number
self.next_number += 1
self.tickets[number] = {"customer": customer, "subject": subject, "severity": severity, "state": "open"}
heapq.heappush(self.to_handle, (severity, number))
self.customers.add(customer)
return number
def handle(self):
if not self.to_handle:
return None
severity, number = heapq.heappop(self.to_handle)
self.tickets[number]["state"] = "closed"
self.closed.append(number)
return number
def undo(self):
if not self.closed:
return None
number = self.closed.pop()
ticket = self.tickets[number]
ticket["state"] = "open"
heapq.heappush(self.to_handle, (ticket["severity"], number))
return number
support = Support()
support.open("Awa", "The panel no longer charges", 2)
support.open("Kofi", "Change my address", 3)
support.open("Lina", "The battery is hot and smoking", 1)
support.open("Awa", "Duplicate invoice", 3)
for _ in range(2):
n = support.handle()
print("handled:", n, support.tickets[n]["subject"])
print("undone:", support.undo())
print("next:", support.handle())
print("still waiting:", sorted(support.to_handle))
handled: 3 The battery is hot and smoking
handled: 1 The panel no longer charges
undone: 1
next: 1
still waiting: [(3, 2), (3, 4)]
Ticket 3 (severity 1) goes before everyone. We undo the closure of ticket 1: it goes back into the heap and, still being the most serious, comes straight out again. Tickets 2 and 4 have the same severity: 2, the older one, will go first.
An undo pops the last closed ticket and puts it back in the queue with its original severity.
Text description of the animation
- The ticket goes into the dictionary, and the customer into the set.
- Its severity of 1 puts it at the front of the heap, ahead of older but less serious tickets.
- handle() takes out the top priority and marks the ticket “closed”.
- The number is put on the stack of closed tickets.
- An undo pops the last closed ticket and puts it back in the queue with its original severity.
Your turn
Worked exercise
Worked exercise: the end-of-day report
Add a report() method to the class that returns a dictionary: the number of open and closed tickets, and the number of tickets still open per severity. It must not change the tickets.
Hint 1
self.tickets.values() only once, and count with d.get(key, 0) + 1.Hint 2
Show the solution and common mistakes
import heapq
class Support:
def __init__(self):
self.tickets, self.to_handle, self.customers, self.closed, self.next_number = {}, [], set(), [], 1
def open(self, customer, subject, severity):
number = self.next_number
self.next_number += 1
self.tickets[number] = {"customer": customer, "subject": subject, "severity": severity, "state": "open"}
heapq.heappush(self.to_handle, (severity, number))
self.customers.add(customer)
return number
def handle(self):
if not self.to_handle:
return None
severity, number = heapq.heappop(self.to_handle)
self.tickets[number]["state"] = "closed"
self.closed.append(number)
return number
def report(self):
states, by_severity = {}, {}
for t in self.tickets.values():
states[t["state"]] = states.get(t["state"], 0) + 1
if t["state"] == "open":
by_severity[t["severity"]] = by_severity.get(t["severity"], 0) + 1
return {"states": states, "open_by_severity": dict(sorted(by_severity.items()))}
support = Support()
for customer, subject, s in [("Awa", "Panel", 2), ("Kofi", "Address", 3), ("Lina", "Battery", 1), ("Mei", "Cable", 2)]:
support.open(customer, subject, s)
support.handle()
print(support.report())
{'states': {'open': 3, 'closed': 1}, 'open_by_severity': {2: 2, 3: 1}}
Common mistakes:
- Counting with
len(self.to_handle): the heap only holds the waiting tickets, and says nothing about the closed ones. - Emptying the heap with
heappopto count: the report would change the data it is supposed to describe.
Project: complete the managerPython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Summary
- 1A real program combines several structures, each chosen for the operation it makes fast.
- 2Heap for priority, dictionary for access by identifier, set for uniqueness, stack for undo.
- 3An increasing number serves both as an identifier and as the arrival order to break ties.
- 4Every operation must keep all the structures consistent: group these updates in methods.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.