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:
- Prefix autocomplete so shoppers get instant product suggestions after typing two or three letters.
- Typo-tolerant query correction so misspelled review terms (
batery,qualty,definately,recieved) map to the right dictionary words. - Dependency-safe pipeline scheduling so indexing jobs always run after their inputs load and any accidental cycle in the pipeline config is rejected immediately.
- 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.
Dataset
Section titled “Dataset”This project uses two files from data/:
data/products.csv— 30 products (P001..P030) with columnsproduct_id,product,category,unit_cost,unit_price,launch_date.data/reviews.csv— 3,000 customer reviews (R00001..R03000) with columnsreview_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.
Requirements
Section titled “Requirements”Your script must:
- Implement
PrefixTriewithinsert(key, label)andautocomplete(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. - Implement
levenshtein(a, b)using dynamic programming with space, plussuggest_word(query, vocabulary, max_dist=2)returning(distance, word)for the closest match (breaking ties alphabetically). - Implement
topological_sort(dependencies)using Kahn’s algorithm with deterministic lexicographical tie-breaking. RaiseValueErrorwhen a cycle exists. Verify cycle detection by testing a cyclic copy of the pipeline graph. - Implement
BloomFilter(expected_items, fp_rate=0.01)backed by abytearray, sizing the bit count and hash count from the standard formulas and using double hashing over SHA-256. - Schedule and execute six pipeline tasks in topological order:
load_productsandload_reviews(no prerequisites)build_trie(depends onload_products)build_bloom(depends onload_reviews)scan_typos(depends onload_products,load_reviews)export_report(depends onbuild_trie,build_bloom,scan_typos)
- During
build_bloom, normalize each review’stextby lowercasing and collapsing whitespace (" ".join(text.lower().split())), compare exact duplicate detections against Bloom filter hits, andassertzero false negatives. - During
scan_typos, count exact lowercase word occurrences indata/reviews.csvfor the six known typos (batery,definately,qualty,recieved,recomend,teh) and match each against the vocabulary["battery", "definitely", "quality", "received", "recommend", "the"]. - Print the exact report below.
Smart Catalog & Pipeline Engine===============================DAG order: 1. load_products 2. load_reviews 3. build_trie 4. build_bloom 5. scan_typos 6. export_reportCycle 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: 7Step plan
Section titled “Step plan”-
Trie index. Create
TrieNode(using__slots__for small memory footprint) andPrefixTrie. Walk character by character on insert and prefix lookup, then collect all labels in the matching subtree with an iterative stack. -
Levenshtein DP. Write the two-row rolling dynamic programming table for
levenshtein(a, b). Add a length-difference fast skipabs(len(word) - len(q)) > max_distinsidesuggest_word(). -
DAG scheduler. Build in-degree counts and reverse adjacency lists in
topological_sort(). Seed adequewith sorted zero-in-degree nodes, append newly unlocked nodes in sorted order, and raiseValueErroriflen(order) != len(indegree). -
Bloom filter. Compute and . Use two 64-bit halves of
hashlib.sha256withh2 |= 1(odd step) so(h1 + i * h2) % myields deterministic bit positions. -
Wire the pipeline. Define the six task functions inside
run_pipeline(), computeorder = topological_sort(dependencies), confirm a cyclic graph raisesValueError, and run each task inorder. -
Verify and refine. Run
python catalog_engine.py, confirm zero false negatives, check every output line against the expected report, and lint withruff.
Starter skeleton:
"""catalog_engine.py: Smart Catalog & Pipeline Engine."""
from __future__ import annotations
import csvimport hashlibimport mathimport refrom collections import Counter, defaultdict, dequefrom 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()Rubric
Section titled “Rubric”| 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 |
| Levenshtein DP | 3 | Exact edit distance with space and length-difference pruning |
| Kahn’s DAG sort | 4 | Deterministic order honoring every prerequisite and raising ValueError on cycles |
| Bloom filter | 4 | Correct 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 |
Stretch goals
Section titled “Stretch goals”- Damerau–Levenshtein transpositions: extend
levenshtein()so adjacent swaps likerecieved->receivedandteh->thehave edit distance 1 instead of 2. - Ranked autocomplete: store each product’s total revenue from
data/sales.csvin the Trie and rank autocomplete results by revenue descending rather than alphabetically. - LRU query cache: wrap
suggest_word()with your own doubly-linked-listLRUCache(capacity 64) and measure the cache hit rate across all 3,000 reviews. - Parallel stage grouping: extend
topological_sort()to return levels (waves of independent tasks that could run concurrently) rather than a flat list. - Unit tests: add a
pytestsuite covering empty Trie queries, self-loop cycles, single-character edits, and Bloom filter false-positive rates acrossfp_ratevalues0.1,0.01, and0.001.
Reference solution
Section titled “Reference solution”Build your own version first, then compare it with the reference implementation below.
Reference solution
"""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 csvimport hashlibimport mathimport refrom collections import Counter, defaultdict, dequefrom 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()Smart Catalog & Pipeline Engine===============================DAG order: 1. load_products 2. load_reviews 3. build_trie 4. build_bloom 5. scan_typos 6. export_reportCycle 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