Skip to content

45. Algorithms and data structures II — Mini-project

An e-commerce search and moderation team maintains a catalog of products and a daily stream of customer reviews. They want one clean, pure-Python engine that runs four jobs in dependency order:

  1. Prefix autocomplete so shoppers get instant product suggestions after typing two or three letters.
  2. Typo-tolerant query correction so misspelled review terms (batery, qualty, definately, recieved) map to the right dictionary words.
  3. Dependency-safe pipeline scheduling so indexing jobs always run after their inputs load and any accidental cycle in the pipeline config is rejected immediately.
  4. Low-memory duplicate detection so repeated review texts are caught with a fixed-size bit array before they enter downstream NLP indexing.

Write a script, catalog_engine.py, that implements all four structures from scratch using only the Python standard library, schedules the stages through Kahn’s topological sort, and prints a deterministic report when run with python catalog_engine.py.

This project uses two files from data/:

  • data/products.csv — 30 products (P001..P030) with columns product_id, product, category, unit_cost, unit_price, launch_date.
  • data/reviews.csv — 3,000 customer reviews (R00001..R03000) with columns review_id, product_id, product, category, rating, title, text, review_date, sentiment. About 170 reviews contain spelling mistakes (batery, definately, qualty, recieved, recomend, teh), and some review texts repeat across customers.

Your script must:

  1. Implement PrefixTrie with insert(key, label) and autocomplete(prefix, limit=3). Index every product’s full lowercase name and every alphanumeric token in its name under the label "{product_id} {product}". Return sorted unique labels.
  2. Implement levenshtein(a, b) using dynamic programming with O(min⁡(∣a∣,∣b∣))O(\min(|a|, |b|)) space, plus suggest_word(query, vocabulary, max_dist=2) returning (distance, word) for the closest match (breaking ties alphabetically).
  3. Implement topological_sort(dependencies) using Kahn’s algorithm with deterministic lexicographical tie-breaking. Raise ValueError when a cycle exists. Verify cycle detection by testing a cyclic copy of the pipeline graph.
  4. Implement BloomFilter(expected_items, fp_rate=0.01) backed by a bytearray, sizing the bit count mm and hash count kk from the standard formulas and using double hashing over SHA-256.
  5. Schedule and execute six pipeline tasks in topological order:
    • load_products and load_reviews (no prerequisites)
    • build_trie (depends on load_products)
    • build_bloom (depends on load_reviews)
    • scan_typos (depends on load_products, load_reviews)
    • export_report (depends on build_trie, build_bloom, scan_typos)
  6. During build_bloom, normalize each review’s text by lowercasing and collapsing whitespace (" ".join(text.lower().split())), compare exact duplicate detections against Bloom filter hits, and assert zero false negatives.
  7. During scan_typos, count exact lowercase word occurrences in data/reviews.csv for the six known typos (batery, definately, qualty, recieved, recomend, teh) and match each against the vocabulary ["battery", "definitely", "quality", "received", "recommend", "the"].
  8. Print the exact report below.
Expected output
Smart Catalog & Pipeline Engine
===============================
DAG order:
1. load_products
2. load_reviews
3. build_trie
4. build_bloom
5. scan_typos
6. export_report
Cycle guard rejected cyclic graph: True
Trie autocomplete (top 3):
'wi' -> P001 Wireless Earbuds
'co' -> P010 Cotton Bed Sheet Set, P015 Organic Cotton T-Shirt, P022 Weeknight Kitchen Cookbook
'sm' -> P003 55-inch 4K Smart TV, P005 Smartwatch Series 5
Review typo scan (Levenshtein distance <= 2):
batery -> battery (dist=1, count=13)
definately -> definitely (dist=1, count=8)
qualty -> quality (dist=1, count=51)
recieved -> received (dist=2, count=1)
recomend -> recommend (dist=1, count=17)
teh -> the (dist=2, count=54)
Bloom filter (28756 bits, 7 hashes) over 3000 reviews:
exact duplicates: 150, Bloom hits: 157, false positives: 7
  1. Trie index. Create TrieNode (using __slots__ for small memory footprint) and PrefixTrie. Walk character by character on insert and prefix lookup, then collect all labels in the matching subtree with an iterative stack.

  2. Levenshtein DP. Write the two-row rolling dynamic programming table for levenshtein(a, b). Add a length-difference fast skip abs(len(word) - len(q)) > max_dist inside suggest_word().

  3. DAG scheduler. Build in-degree counts and reverse adjacency lists in topological_sort(). Seed a deque with sorted zero-in-degree nodes, append newly unlocked nodes in sorted order, and raise ValueError if len(order) != len(indegree).

  4. Bloom filter. Compute m=⌈−nln⁡(p)/(ln⁡2)2⌉m = \lceil -n \ln(p) / (\ln 2)^2 \rceil and k=round((m/n)ln⁡2)k = \text{round}((m / n) \ln 2). Use two 64-bit halves of hashlib.sha256 with h2 |= 1 (odd step) so (h1 + i * h2) % m yields kk deterministic bit positions.

  5. Wire the pipeline. Define the six task functions inside run_pipeline(), compute order = topological_sort(dependencies), confirm a cyclic graph raises ValueError, and run each task in order.

  6. Verify and refine. Run python catalog_engine.py, confirm zero false negatives, check every output line against the expected report, and lint with ruff.

Starter skeleton:

catalog_engine.py (starter)
"""catalog_engine.py: Smart Catalog & Pipeline Engine."""
from __future__ import annotations
import csv
import hashlib
import math
import re
from collections import Counter, defaultdict, deque
from collections.abc import Callable
class PrefixTrie:
"""Prefix index mapping lowercase keys to sorted product labels."""
def __init__(self) -> None:
... # TODO: initialize root TrieNode
def insert(self, key: str, label: str) -> None:
... # TODO: walk characters and store unique label
def autocomplete(self, prefix: str, limit: int = 3) -> list[str]:
... # TODO: walk prefix, DFS subtree, return sorted(found)[:limit]
def levenshtein(a: str, b: str) -> int:
... # TODO: rolling-row 2D DP edit distance
def topological_sort(dependencies: dict[str, list[str]]) -> list[str]:
... # TODO: Kahn's algorithm with ValueError on cycles
class BloomFilter:
"""Fixed-size bit-array Bloom filter using double hashing over SHA-256."""
def __init__(self, expected_items: int, fp_rate: float = 0.01) -> None:
... # TODO: compute num_bits, num_hashes, bytearray
def add(self, text: str) -> None:
... # TODO: set k bits
def __contains__(self, text: str) -> bool:
... # TODO: check all k bits are 1
def run_pipeline(
products_path: str = "data/products.csv",
reviews_path: str = "data/reviews.csv",
) -> None:
... # TODO: schedule and execute the six tasks and print the report
if __name__ == "__main__":
run_pipeline()
Criterion Points Full points when
Runs cleanly 2 python catalog_engine.py exits with code 0 and matches the expected report
PrefixTrie 3 Inserts full names and word tokens; returns sorted unique matches in O(L+subtree)O(L + \text{subtree})
Levenshtein DP 3 Exact edit distance with O(min⁡(m,n))O(\min(m, n)) space and length-difference pruning
Kahn’s DAG sort 4 Deterministic order honoring every prerequisite and raising ValueError on cycles
Bloom filter 4 Correct (m,k)(m, k) sizing, bit-level bytearray ops, deterministic hashes, 0 false negatives
Pipeline integration 2 Tasks execute strictly in the topological order returned by topological_sort()
Code quality 2 Full type hints, docstrings, if __name__ == "__main__":, ruff-clean
Total 20 16 or more: ready for Module 46
  1. Damerau–Levenshtein transpositions: extend levenshtein() so adjacent swaps like recieved -> received and teh -> the have edit distance 1 instead of 2.
  2. Ranked autocomplete: store each product’s total revenue from data/sales.csv in the Trie and rank autocomplete results by revenue descending rather than alphabetically.
  3. LRU query cache: wrap suggest_word() with your own doubly-linked-list LRUCache (capacity 64) and measure the cache hit rate across all 3,000 reviews.
  4. Parallel stage grouping: extend topological_sort() to return levels (waves of independent tasks that could run concurrently) rather than a flat list.
  5. Unit tests: add a pytest suite covering empty Trie queries, self-loop cycles, single-character edits, and Bloom filter false-positive rates across fp_rate values 0.1, 0.01, and 0.001.

Build your own version first, then compare it with the reference implementation below.

Reference solution
catalog_engine.py
"""catalog_engine.py: Smart Catalog & Pipeline Engine.
Combines four Module 45 structures on the course datasets:
1. A Trie for fast product-name and word-prefix autocomplete.
2. Levenshtein edit distance (2D DP) for typo-tolerant search suggestions.
3. Kahn's topological sort for DAG pipeline scheduling and cycle detection.
4. A Bloom filter for low-memory duplicate detection over review texts.
"""
from __future__ import annotations
import csv
import hashlib
import math
import re
from collections import Counter, defaultdict, deque
from collections.abc import Callable
class TrieNode:
"""One node in a character Trie."""
__slots__ = ("children", "items")
def __init__(self) -> None:
self.children: dict[str, TrieNode] = {}
self.items: list[str] = []
class PrefixTrie:
"""Prefix index mapping lowercase keys to sorted product labels."""
def __init__(self) -> None:
self.root = TrieNode()
def insert(self, key: str, label: str) -> None:
node = self.root
for ch in key.lower():
node = node.children.setdefault(ch, TrieNode())
if label not in node.items:
node.items.append(label)
def autocomplete(self, prefix: str, limit: int = 3) -> list[str]:
"""Return up to `limit` unique labels matching `prefix`."""
node = self.root
for ch in prefix.lower():
if ch not in node.children:
return []
node = node.children[ch]
found: set[str] = set()
stack = [node]
while stack:
cur = stack.pop()
found.update(cur.items)
for child in cur.children.values():
stack.append(child)
return sorted(found)[:limit]
def levenshtein(a: str, b: str) -> int:
"""Compute Levenshtein edit distance with O(min(len(a), len(b))) space."""
if len(a) < len(b):
a, b = b, a
prev = list(range(len(b) + 1))
for i, ch_a in enumerate(a, start=1):
curr = [i] + [0] * len(b)
for j, ch_b in enumerate(b, start=1):
cost = 0 if ch_a == ch_b else 1
curr[j] = min(
prev[j] + 1, # delete
curr[j - 1] + 1, # insert
prev[j - 1] + cost, # substitute
)
prev = curr
return prev[-1]
def suggest_word(
query: str, vocabulary: list[str], max_dist: int = 2
) -> tuple[int, str] | None:
"""Return the closest (distance, word) within `max_dist` edits, or None."""
q = query.lower()
best: tuple[int, str] | None = None
for word in vocabulary:
if abs(len(word) - len(q)) > max_dist:
continue
dist = levenshtein(q, word)
if dist <= max_dist and (best is None or (dist, word) < best):
best = (dist, word)
return best
def topological_sort(dependencies: dict[str, list[str]]) -> list[str]:
"""Return a deterministic execution order using Kahn's algorithm.
`dependencies[task]` lists tasks that must finish before `task` starts.
Raises ValueError if the graph contains a cycle.
"""
indegree: dict[str, int] = {task: 0 for task in dependencies}
dependents: dict[str, list[str]] = defaultdict(list)
for task, prereqs in dependencies.items():
for prereq in prereqs:
if prereq not in indegree:
indegree[prereq] = 0
dependents[prereq].append(task)
indegree[task] += 1
ready = deque(sorted(t for t, deg in indegree.items() if deg == 0))
order: list[str] = []
while ready:
current = ready.popleft()
order.append(current)
newly_ready = []
for nxt in dependents[current]:
indegree[nxt] -= 1
if indegree[nxt] == 0:
newly_ready.append(nxt)
for nxt in sorted(newly_ready):
ready.append(nxt)
if len(order) != len(indegree):
remaining = sorted(t for t, deg in indegree.items() if deg > 0)
raise ValueError(f"Cycle detected involving: {', '.join(remaining)}")
return order
class BloomFilter:
"""Fixed-size bit-array Bloom filter using double hashing over SHA-256."""
def __init__(self, expected_items: int, fp_rate: float = 0.01) -> None:
m = -expected_items * math.log(fp_rate) / (math.log(2) ** 2)
self.num_bits = max(64, int(math.ceil(m)))
k = int(round((self.num_bits / expected_items) * math.log(2)))
self.num_hashes = max(1, k)
self.bits = bytearray((self.num_bits + 7) // 8)
def _positions(self, text: str) -> list[int]:
digest = hashlib.sha256(text.encode("utf-8")).digest()
h1 = int.from_bytes(digest[:8], "big")
h2 = int.from_bytes(digest[8:16], "big") | 1
return [(h1 + i * h2) % self.num_bits for i in range(self.num_hashes)]
def add(self, text: str) -> None:
for pos in self._positions(text):
self.bits[pos // 8] |= 1 << (pos % 8)
def __contains__(self, text: str) -> bool:
return all(
(self.bits[pos // 8] >> (pos % 8)) & 1 for pos in self._positions(text)
)
def normalize_text(text: str) -> str:
"""Lowercase and collapse whitespace for duplicate detection."""
return " ".join(text.lower().split())
def run_pipeline(
products_path: str = "data/products.csv",
reviews_path: str = "data/reviews.csv",
) -> None:
"""Schedule and execute the Smart Catalog & Pipeline Engine."""
dependencies = {
"load_products": [],
"load_reviews": [],
"build_trie": ["load_products"],
"build_bloom": ["load_reviews"],
"scan_typos": ["load_products", "load_reviews"],
"export_report": ["build_trie", "build_bloom", "scan_typos"],
}
order = topological_sort(dependencies)
# Confirm cycle detection rejects an invalid dependency graph.
cyclic = dict(dependencies)
cyclic["load_products"] = ["export_report"]
cycle_rejected = False
try:
topological_sort(cyclic)
except ValueError:
cycle_rejected = True
assert cycle_rejected
products: list[dict[str, str]] = []
reviews: list[dict[str, str]] = []
trie = PrefixTrie()
bloom_stats: dict[str, int] = {}
typo_report: list[tuple[str, str, int, int]] = []
def load_products() -> None:
with open(products_path, newline="", encoding="utf-8") as f:
products.extend(csv.DictReader(f))
def load_reviews() -> None:
with open(reviews_path, newline="", encoding="utf-8") as f:
reviews.extend(csv.DictReader(f))
def build_trie() -> None:
for row in products:
label = f"{row['product_id']} {row['product']}"
trie.insert(row["product"], label)
for token in re.findall(r"[a-z0-9]+", row["product"].lower()):
trie.insert(token, label)
def build_bloom() -> None:
bloom = BloomFilter(expected_items=len(reviews), fp_rate=0.01)
exact_seen: set[str] = set()
exact_dupes = 0
bloom_dupes = 0
false_negatives = 0
for row in reviews:
norm = normalize_text(row["text"])
in_exact = norm in exact_seen
in_bloom = norm in bloom
if in_exact:
exact_dupes += 1
if not in_bloom:
false_negatives += 1
if in_bloom:
bloom_dupes += 1
exact_seen.add(norm)
bloom.add(norm)
assert false_negatives == 0
bloom_stats.update(
{
"bits": bloom.num_bits,
"hashes": bloom.num_hashes,
"total": len(reviews),
"exact_dupes": exact_dupes,
"bloom_dupes": bloom_dupes,
"false_positives": bloom_dupes - exact_dupes,
}
)
def scan_typos() -> None:
counts: Counter[str] = Counter()
for row in reviews:
counts.update(re.findall(r"[a-z]+", row["text"].lower()))
vocab = sorted(
{
"battery",
"definitely",
"quality",
"received",
"recommend",
"the",
}
)
known_typos = ["batery", "definately", "qualty", "recieved", "recomend", "teh"]
for typo in known_typos:
hit = suggest_word(typo, vocab, max_dist=2)
assert hit is not None
dist, fix = hit
typo_report.append((typo, fix, dist, counts[typo]))
def export_report() -> None:
print("Smart Catalog & Pipeline Engine")
print("===============================")
print("DAG order:")
for step_no, name in enumerate(order, start=1):
print(f" {step_no}. {name}")
print(f"Cycle guard rejected cyclic graph: {cycle_rejected}")
print()
print("Trie autocomplete (top 3):")
for prefix in ("wi", "co", "sm"):
matches = ", ".join(trie.autocomplete(prefix, limit=3))
print(f" '{prefix}' -> {matches}")
print()
print("Review typo scan (Levenshtein distance <= 2):")
for typo, fix, dist, count in typo_report:
print(f" {typo:<10} -> {fix:<10} (dist={dist}, count={count})")
print()
print(
f"Bloom filter ({bloom_stats['bits']} bits, {bloom_stats['hashes']} hashes)"
f" over {bloom_stats['total']} reviews:"
)
print(
f" exact duplicates: {bloom_stats['exact_dupes']}, "
f"Bloom hits: {bloom_stats['bloom_dupes']}, "
f"false positives: {bloom_stats['false_positives']}"
)
tasks: dict[str, Callable[[], None]] = {
"load_products": load_products,
"load_reviews": load_reviews,
"build_trie": build_trie,
"build_bloom": build_bloom,
"scan_typos": scan_typos,
"export_report": export_report,
}
for task_name in order:
tasks[task_name]()
if __name__ == "__main__":
run_pipeline()
Output
Smart Catalog & Pipeline Engine
===============================
DAG order:
1. load_products
2. load_reviews
3. build_trie
4. build_bloom
5. scan_typos
6. export_report
Cycle guard rejected cyclic graph: True
Trie autocomplete (top 3):
'wi' -> P001 Wireless Earbuds
'co' -> P010 Cotton Bed Sheet Set, P015 Organic Cotton T-Shirt, P022 Weeknight Kitchen Cookbook
'sm' -> P003 55-inch 4K Smart TV, P005 Smartwatch Series 5
Review typo scan (Levenshtein distance <= 2):
batery -> battery (dist=1, count=13)
definately -> definitely (dist=1, count=8)
qualty -> quality (dist=1, count=51)
recieved -> received (dist=2, count=1)
recomend -> recommend (dist=1, count=17)
teh -> the (dist=2, count=54)
Bloom filter (28756 bits, 7 hashes) over 3000 reviews:
exact duplicates: 150, Bloom hits: 157, false positives: 7