Practical Projects Practice Questions
Level 1: Core Fundamentals & Arithmetic Parsers (Questions 1–10)
Question 1: Support for Floating-Point Numbers
Write a function parse_and_add(expr) that parses a basic arithmetic addition or subtraction string containing decimal floats and returns the calculated result.
main.pyRunnable## Solution def parse_and_add(expr: str) -> float: expr = expr.replace(" ", "") if "+" in expr: left, right = expr.split("+") return float(left) + float(right) elif "-" in expr: left, right = expr.split("-") return float(left) - float(right) return float(expr) ## Verification print(f"Result: {parse_and_add('12.5 + 4.5')}")
Expected Output:
Result: 17.0
Question 2: Memory Storage Class (M+, MR)
Create a stateful CalculatorMemory class that simulates physical calculator memory registers (memory float) initialized to 0.0 with add(val) and recall() methods.
main.pyRunnable## Solution class CalculatorMemory: def __init__(self): self._memory = 0.0 def add(self, val: float): self._memory += val def recall(self) -> float: return self._memory ## Verification mem = CalculatorMemory() mem.add(10.5) mem.add(5.25) print(f"Stored Memory: {mem.recall()}")
Expected Output:
Stored Memory: 15.75
Question 3: Division-by-Zero Exception Isolation
Create a robust division wrapper safe_divide(a, b) that performs float division, catching any ZeroDivisionError and returning a string flag "Infinity" instead of crashing.
main.pyRunnable## Solution def safe_divide(a: float, b: float) -> float | str: try: return a / b except ZeroDivisionError: return "Infinity" ## Verification print(f"Valid: {safe_divide(10, 2)}") print(f"Zero Div: {safe_divide(10, 0)}")
Expected Output:
Valid: 5.0
Zero Div: Infinity
Question 4: Basic History Logging
Implement a CalculatorHistory class that records math operations as string expressions and displays them via a get_log() method.
main.pyRunnable## Solution class CalculatorHistory: def __init__(self): self.history = [] def log(self, expr: str, result: float): self.history.append(f"{expr} = {result}") def get_log(self) -> list[str]: return self.history ## Verification hist = CalculatorHistory() hist.log("5 * 4", 20.0) hist.log("10 / 2", 5.0) print(hist.get_log())
Expected Output:
['5 * 4 = 20.0', '10 / 2 = 5.0']
Question 5: Modulo and Integer Division Parser
Extend your basic string parser to handle modulo % and integer division // operations for positive numbers.
main.pyRunnable## Solution def parse_division_ops(expr: str) -> int: expr = expr.replace(" ", "") if "//" in expr: left, right = expr.split("//") return int(left) // int(right) elif "%" in expr: left, right = expr.split("%") return int(left) % int(right) return int(expr) ## Verification print(f"Integer Div: {parse_division_ops('25 // 4')}") print(f"Modulo: {parse_division_ops('25 % 4')}")
Expected Output:
Integer Div: 6
Modulo: 1
Question 6: Percentages Evaluator
Write a function parse_percentage(expr) that processes a string calculation of a percent value (e.g. "20% of 150") and returns the absolute float value.
main.pyRunnable## Solution def parse_percentage(expr: str) -> float: parts = expr.lower().split("of") pct_val = float(parts[0].replace("%", "").strip()) total_val = float(parts[1].strip()) return (pct_val / 100.0) * total_val ## Verification print(f"Result: {parse_percentage('15% of 200')}")
Expected Output:
Result: 30.0
Question 7: String Expressions Cleaner
Write a sanitation function clean_expression(expr) that strips all alphabetic characters and malicious identifiers from a math input string, preserving only digits, operators, and decimal points.
main.pyRunnable## Solution def clean_expression(expr: str) -> str: allowed = "0123456789+-*/.() " return "".join(char for char in expr if char in allowed) ## Verification print(f"Cleaned: '{clean_expression('import os; 3.14 * 2 + val')}'")
Expected Output:
Cleaned: ' 3.14 * 2 + '
Question 8: Simple RPN Evaluator
Write a function evaluate_rpn(tokens) that evaluates basic postfix notation (Reverse Polish Notation) expressions using a list as a stack. Support +, -, and *.
main.pyRunnable## Solution def evaluate_rpn(tokens: list[str]) -> float: stack = [] for token in tokens: if token in ("+", "-", "*"): b = stack.pop() a = stack.pop() if token == "+": stack.append(a + b) elif token == "-": stack.append(a - b) elif token == "*": stack.append(a * b) else: stack.append(float(token)) return stack[0] ## Verification print(f"RPN Result: {evaluate_rpn(['3', '4', '2', '*', '+'])}")
Expected Output:
RPN Result: 11.0
Question 9: Clear Memory Register
Add a clear() method to your CalculatorMemory class that resets the private _memory register back to 0.0.
main.pyRunnable## Solution class CalculatorMemoryEnhanced(CalculatorMemory): def clear(self): self._memory = 0.0 ## Verification mem = CalculatorMemoryEnhanced() mem.add(55.5) mem.clear() print(f"Cleared Memory: {mem.recall()}")
Expected Output:
Cleared Memory: 0.0
Question 10: Parentheses Balance Checker
Write a parser pre-check function are_parentheses_balanced(expr) that uses a list stack to verify if mathematical brackets are properly nested.
main.pyRunnable## Solution def are_parentheses_balanced(expr: str) -> bool: stack = [] for char in expr: if char == "(": stack.append(char) elif char == ")": if not stack: return False stack.pop() return len(stack) == 0 ## Verification print(f"Balanced: {are_parentheses_balanced('(3 + 5) * (2 - 1)')}") print(f"Imbalanced: {are_parentheses_balanced('((3 + 5)')")
Expected Output:
Balanced: True
Imbalanced: False
Progress Check (Level 1)
Level 2: Text Sanitation, Custom Formatting & Corpus Mapping (Questions 11–20)
Question 11: Text Word Count & Sanitation
Write a function sanitize_and_count(text) that strips punctuation characters (.,!?;:"()), converts text to lowercase, splits it, and returns the sanitized word count.
main.pyRunnable## Solution def sanitize_and_count(text: str) -> int: punctuation = '.,!?;:"()' cleaned = "".join(char.lower() for char in text if char not in punctuation) return len(cleaned.split()) ## Verification sample = "Hello, world! This is a clean, sanitized text block." print(f"Sanitized Word Count: {sanitize_and_count(sample)}")
Expected Output:
Sanitized Word Count: 9
Question 12: Unique Word Finder
Write a function get_unique_words(text) that sanitizes a corpus string and returns a set of all unique words.
main.pyRunnable## Solution def get_unique_words(text: str) -> set[str]: punctuation = '.,!?;:"()' cleaned = "".join(char.lower() for char in text if char not in punctuation) return set(cleaned.split()) ## Verification sample = "Apple banana apple orange banana orange grape" print(f"Unique Words: {sorted(list(get_unique_words(sample)))}")
Expected Output:
Unique Words: ['apple', 'banana', 'grape', 'orange']
Question 13: Stop-words Filtering Pipeline
Write a function filter_stopwords(words, stopwords) that returns a list of words, removing common words in the stopwords set.
main.pyRunnable## Solution def filter_stopwords(words: list[str], stopwords: set[str]) -> list[str]: return [w for w in words if w.lower() not in stopwords] ## Verification word_list = ["Python", "is", "a", "highly", "expressive", "language"] stops = {"is", "a", "the", "an"} print(f"Filtered: {filter_stopwords(word_list, stops)}")
Expected Output:
Filtered: ['Python', 'highly', 'expressive', 'language']
Question 14: Top N Words Extractor
Write a function get_top_n_words(text, n) that calculates word frequencies, sorting them descending by count, and returns the top occurrences as list of tuples.
main.pyRunnable## Solution def get_top_n_words(text: str, n: int) -> list[tuple[str, int]]: punctuation = '.,!?;:"()' cleaned = "".join(char.lower() for char in text if char not in punctuation) words = cleaned.split() freq = {} for w in words: freq[w] = freq.get(w, 0) + 1 sorted_freq = sorted(freq.items(), key=lambda x: (-x[1], x[0])) return sorted_freq[:n] ## Verification sample = "data data logic syntax logic code data compile syntax logic data" print(f"Top 2: {get_top_n_words(sample, 2)}")
Expected Output:
Top 2: [('data', 4), ('logic', 3)]
Question 15: Readability Index (Sentence Counter)
Write a function count_sentences(text) that counts sentences by detecting terminal characters: ., !, and ?.
main.pyRunnable## Solution def count_sentences(text: str) -> int: delimiters = (".", "!", "?") count = sum(text.count(d) for d in delimiters) return max(count, 1) ## Verification sample = "First statement! Second statement? Third statement." print(f"Sentences: {count_sentences(sample)}")
Expected Output:
Sentences: 3
Question 16: Standard Syllable Counter Heuristic
Write a function count_syllables_heuristic(word) that counts vowel clusters to estimate the syllables of a single word.
main.pyRunnable## Solution def count_syllables_heuristic(word: str) -> int: word = word.lower().strip(".,!?;:") if not word: return 0 vowels = "aeiouy" count = 0 prev_vowel = False for char in word: is_vowel = char in vowels if is_vowel and not prev_vowel: count += 1 prev_vowel = is_vowel if word.endswith("e") and count > 1: count -= 1 return max(count, 1) ## Verification print(f"syllable: {count_syllables_heuristic('syllable')}") print(f"code: {count_syllables_heuristic('code')}")
Expected Output:
syllable: 3
code: 1
Question 17: Paragraph Statistics Tracker
Write a function analyze_paragraphs(text) that counts the paragraphs separated by blank lines ("\n\n"), and returns a dictionary of metrics: { "paragraphs": int, "avg_words_per_paragraph": float }.
main.pyRunnable## Solution def analyze_paragraphs(text: str) -> dict: paragraphs = [p.strip() for p in text.split("\n\n") if p.strip()] p_count = len(paragraphs) if p_count == 0: return {"paragraphs": 0, "avg_words_per_paragraph": 0.0} total_words = sum(len(p.split()) for p in paragraphs) return { "paragraphs": p_count, "avg_words_per_paragraph": total_words / p_count } ## Verification sample = "Paragraph one starts here.\n\nParagraph two is slightly longer." print(analyze_paragraphs(sample))
Expected Output:
{'paragraphs': 2, 'avg_words_per_paragraph': 4.5}
Question 18: File Path Verification Loop
Write a function get_valid_corpus_path(filepath) using pathlib.Path to check if a file exists and is a regular file, raising a FileNotFoundError with a custom error message if it does not.
main.pyRunnable## Solution from pathlib import Path def get_valid_corpus_path(filepath: str) -> Path: path = Path(filepath) if not path.is_file(): raise FileNotFoundError(f"Corpus file does not exist at '{filepath}'") return path ## Verification try: get_valid_corpus_path("non_existent_corpus.txt") except FileNotFoundError as e: print(e)
Expected Output:
Corpus file does not exist at 'non_existent_corpus.txt'
Question 19: Long Words Searcher
Write a function find_long_words(text, threshold) that filters and returns a unique set of all words containing more than threshold character length.
main.pyRunnable## Solution def find_long_words(text: str, threshold: int) -> set[str]: punctuation = '.,!?;:"()' cleaned = "".join(char.lower() for char in text if char not in punctuation) return {w for w in cleaned.split() if len(w) > threshold} ## Verification sample = "This is a demonstration of alphabetical word filtering." print(find_long_words(sample, 8))
Expected Output:
{'demonstration', 'alphabetical'}
Question 20: Flesch Reading Score Calculator
Write a function calculate_flesch_index(words, sentences, syllables) that implements the Flesch Reading Ease index: .
main.pyRunnable## Solution def calculate_flesch_index(words: int, sentences: int, syllables: int) -> float: if words == 0 or sentences == 0: return 0.0 asl = words / sentences asw = syllables / words return 206.835 - (1.015 * asl) - (84.6 * asw) ## Verification print(f"Flesch Score: {calculate_flesch_index(100, 5, 150):.2f}")
Expected Output:
Flesch Score: 59.64
Progress Check (Level 2)
Level 3: Stateful Application Logic & Data Streams (Questions 21–30)
Question 21: Private State Encapsulation
Create an InventoryItem class that keeps the unit _cost private, enforcing validation via getters and setters so that unit cost can never be negative.
main.pyRunnable## Solution class InventoryItem: def __init__(self, name: str, cost: float): self.name = name self._cost = 0.0 self.cost = cost # trigger setter @property def cost(self) -> float: return self._cost @cost.setter def cost(self, val: float): if val < 0.0: raise ValueError("Unit cost cannot be negative.") self._cost = val ## Verification try: item = InventoryItem("Processor", -150.0) except ValueError as e: print(f"Validation Guarded: {e}")
Expected Output:
Validation Guarded: Unit cost cannot be negative.
Question 22: Stock Threshold Warning
Extend your InventoryItem class to hold a quantity and a threshold integer. Write a method is_low_stock() that returns True if quantity falls below or matches the threshold.
main.pyRunnable## Solution class InventoryItemThreshold(InventoryItem): def __init__(self, name: str, cost: float, quantity: int, threshold: int): super().__init__(name, cost) self.quantity = quantity self.threshold = threshold def is_low_stock(self) -> bool: return self.quantity <= self.threshold ## Verification item = InventoryItemThreshold("Microcontroller", 2.50, 3, 5) print(f"Low Stock Triggered: {item.is_low_stock()}")
Expected Output:
Low Stock Triggered: True
Question 23: Stateful Warehouse Inventory Registry
Create a class Warehouse that holds a dictionary of InventoryItem instances mapped by SKU key. Write a method register_item(sku, item) to append items to the database.
main.pyRunnable## Solution class Warehouse: def __init__(self): self.catalog = {} def register_item(self, sku: str, item: InventoryItem): self.catalog[sku.upper()] = item def get_item(self, sku: str) -> InventoryItem: return self.catalog.get(sku.upper()) ## Verification w = Warehouse() w.register_item("MCU-100", InventoryItem("MCU-100", 5.00)) print(f"SKU Found: {w.get_item('MCU-100').name}")
Expected Output:
SKU Found: MCU-100
Question 24: Standard Dispatch Deduction
Write a method ship_stock(sku, quantity) on your Warehouse class that decreases an item's quantity by the requested count, raising a ValueError if there are insufficient stock levels.
main.pyRunnable## Solution class StatefulWarehouse(Warehouse): def ship_stock(self, sku: str, quantity: int): item = self.get_item(sku) if not item: raise KeyError("SKU not catalogued.") if item.quantity < quantity: raise ValueError("Insufficient stock levels.") item.quantity -= quantity ## Verification w = StatefulWarehouse() item = InventoryItemThreshold("Resistor", 0.05, 100, 10) w.register_item("RES-001", item) try: w.ship_stock("RES-001", 150) except ValueError as e: print(f"Failed Ship Check: {e}")
Expected Output:
Failed Ship Check: Insufficient stock levels.
Question 25: Inventory Valuation Sum
Write a method calculate_total_value() on your Warehouse class that aggregates the value (unit cost quantity) of all inventory assets catalogued.
main.pyRunnable## Solution class ValuationWarehouse(Warehouse): def calculate_total_value(self) -> float: return sum(item.cost * item.quantity for item in self.catalog.values()) ## Verification w = ValuationWarehouse() w.register_item("SKU-1", InventoryItemThreshold("Board", 10.00, 5, 2)) w.register_item("SKU-2", InventoryItemThreshold("Capacitor", 2.50, 20, 5)) print(f"Total Valuation: ${w.calculate_total_value():.2f}")
Expected Output:
Total Valuation: $100.00
Question 26: Transaction Log Trace
Extend the Warehouse class to record stock modifications (replenishment or dispatch) into a private transaction log list, tracking changes as dictionaries.
main.pyRunnable## Solution class LoggingWarehouse(Warehouse): def __init__(self): super().__init__() self._logs = [] def record_change(self, sku: str, action: str, amount: int): self._logs.append({ "sku": sku, "action": action, "amount": amount }) def get_logs(self) -> list[dict]: return self._logs ## Verification w = LoggingWarehouse() w.record_change("RES-01", "REPLENISH", 500) print(w.get_logs())
Expected Output:
[{'sku': 'RES-01', 'action': 'REPLENISH', 'amount': 500}]
Question 27: Bulk Replenishment Stream
Write a method bulk_replenish(shipments) on your Warehouse class that processes a list of SKU and quantity tuples, updating quantities dynamically.
main.pyRunnable## Solution class BulkWarehouse(Warehouse): def bulk_replenish(self, shipments: list[tuple[str, int]]): for sku, qty in shipments: item = self.get_item(sku) if item: item.quantity += qty ## Verification w = BulkWarehouse() i1 = InventoryItemThreshold("Relay", 15.0, 10, 2) i2 = InventoryItemThreshold("Sensor", 8.0, 5, 1) w.register_item("REL-01", i1) w.register_item("SEN-02", i2) w.bulk_replenish([("REL-01", 5), ("SEN-02", 10)]) print(f"REL-01: {i1.quantity}, SEN-02: {i2.quantity}")
Expected Output:
REL-01: 15, SEN-02: 15
Question 28: Stock SKU Reorder Filter
Write a method get_reorder_list() on your Warehouse class that returns a list of SKUs for all catalogued items currently flagged as low-stock.
main.pyRunnable## Solution class FilterWarehouse(Warehouse): def get_reorder_list(self) -> list[str]: return [sku for sku, item in self.catalog.items() if item.is_low_stock()] ## Verification w = FilterWarehouse() w.register_item("A", InventoryItemThreshold("Part A", 5.0, 1, 5)) w.register_item("B", InventoryItemThreshold("Part B", 10.0, 20, 5)) print(f"Reorder Needed: {w.get_reorder_list()}")
Expected Output:
Reorder Needed: ['A']
Question 29: Dynamic Supplier Mapping
Add a supplier metadata attribute to InventoryItem. Implement a method get_items_by_supplier(supplier_name) on your Warehouse class that yields all items matching that supplier.
main.pyRunnable## Solution class SuppliedItem(InventoryItemThreshold): def __init__(self, name: str, cost: float, quantity: int, threshold: int, supplier: str): super().__init__(name, cost, quantity, threshold) self.supplier = supplier class SuppliedWarehouse(Warehouse): def get_items_by_supplier(self, supplier: str) -> list[SuppliedItem]: return [item for item in self.catalog.values() if getattr(item, 'supplier', '').lower() == supplier.lower()] ## Verification w = SuppliedWarehouse() w.register_item("A", SuppliedItem("Lens", 50.0, 5, 2, "Supplier-X")) w.register_item("B", SuppliedItem("Mirror", 30.0, 10, 2, "Supplier-Y")) print(f"Supplier-X item count: {len(w.get_items_by_supplier('Supplier-X'))}")
Expected Output:
Supplier-X item count: 1
Question 30: Inventory Item De-registration
Implement a method deregister_item(sku) on your Warehouse class that completely removes a SKU catalog record from the database dict, returning the deleted item object.
main.pyRunnable## Solution class EditableWarehouse(Warehouse): def deregister_item(self, sku: str) -> InventoryItem: return self.catalog.pop(sku.upper(), None) ## Verification w = EditableWarehouse() w.register_item("DEV-1", InventoryItem("Development Board", 45.00)) removed = w.deregister_item("DEV-1") print(f"Removed SKU: {removed.name if removed else None}, Size: {len(w.catalog)}")
Expected Output:
Removed SKU: Development Board, Size: 0
Progress Check (Level 3)
Level 4: Custom Serialization, JSON, & Persistent Vaults (Questions 31–40)
Question 31: Single Item JSON Dictionary Converter
Write a method to_dict() on your InventoryItem class that transforms its attributes into a standard dictionary.
main.pyRunnable## Solution class SerializedItem(InventoryItemThreshold): def to_dict(self) -> dict: return { "name": self.name, "cost": self.cost, "quantity": self.quantity, "threshold": self.threshold } ## Verification item = SerializedItem("Daughterboard", 12.00, 10, 2) print(item.to_dict())
Expected Output:
{'name': 'Daughterboard', 'cost': 12.0, 'quantity': 10, 'threshold': 2}
Question 32: Dictionary-to-Object Factory Constructor
Implement a class-method constructor from_dict(cls, data) on SerializedItem that returns a class instance populated with attributes inside the passed dictionary.
main.pyRunnable## Solution class SerializedItemFactory(SerializedItem): @classmethod def from_dict(cls, data: dict) -> "SerializedItemFactory": return cls( name=data["name"], cost=data["cost"], quantity=data["quantity"], threshold=data["threshold"] ) ## Verification serialized = {"name": "Switch", "cost": 4.50, "quantity": 100, "threshold": 5} item = SerializedItemFactory.from_dict(serialized) print(f"Constructed SKU Instance: {item.name} (${item.cost})")
Expected Output:
Constructed SKU Instance: Switch ($4.5)
Question 33: Complete Warehouse JSON Database Dump
Write a method export_json(filepath) on your Warehouse class that converts all catalogued items into raw dictionaries, writing the serialized output into a structured JSON file.
main.pyRunnable## Solution import json class ExportWarehouse(Warehouse): def export_json(self, filepath: str): payload = {} for sku, item in self.catalog.items(): payload[sku] = { "name": item.name, "cost": item.cost, "quantity": getattr(item, 'quantity', 0), "threshold": getattr(item, 'threshold', 0) } with open(filepath, "w", encoding="utf-8") as file: json.dump(payload, file, indent=4) ## Verification w = ExportWarehouse() w.register_item("CHIP-8", SerializedItemFactory("Processor-8", 1.25, 50, 10)) w.export_json("warehouse_export.json") with open("warehouse_export.json", "r") as file: print(file.read().strip())
Expected Output:
{ "CHIP-8": { "name": "Processor-8", "cost": 1.25, "quantity": 50, "threshold": 10 } }
Question 34: JSON Database Loader
Write a method import_json(filepath) on your Warehouse class that loads data from a JSON file, deserializing and populating the warehouse instance list.
main.pyRunnable## Solution class ImportWarehouse(Warehouse): def import_json(self, filepath: str): with open(filepath, "r", encoding="utf-8") as file: payload = json.load(file) self.catalog.clear() for sku, data in payload.items(): self.catalog[sku] = SerializedItemFactory( name=data["name"], cost=data["cost"], quantity=data["quantity"], threshold=data["threshold"] ) ## Verification w = ImportWarehouse() w.import_json("warehouse_export.json") print(f"Imported SKU Count: {len(w.catalog)}, Chip Name: {w.get_item('CHIP-8').name}")
Expected Output:
Imported SKU Count: 1, Chip Name: Processor-8
Question 35: File Locking Handler Check
Write a function safe_open_database(filepath) that opens a database file, catching standard system-level exceptions and printing a formatted warning instead of raising an unhandled failure.
main.pyRunnable## Solution def safe_open_database(filepath: str) -> str: try: with open(filepath, "r", encoding="utf-8") as file: return file.read() except FileNotFoundError: return "[Failure] Database file path not found." except OSError as e: return f"[Failure] OS level error: {e}" ## Verification print(safe_open_database("missing_registry_vault.json"))
Expected Output:
[Failure] Database file path not found.
Question 36: Encrypted JSON Backup (Mock)
Write a function export_encrypted(data, filepath, key) that performs a simple XOR calculation (with integer key) on a JSON string representing the database, saving the resulting integer list.
main.pyRunnable## Solution def export_encrypted(data: dict, filepath: str, key: int): json_str = json.dumps(data) encrypted = [ord(char) ^ key for char in json_str] with open(filepath, "w", encoding="utf-8") as file: json.dump(encrypted, file) ## Verification db = {"sku": "A", "stock": 5} export_encrypted(db, "db_crypt.json", 42) with open("db_crypt.json", "r") as file: print(file.read()[:50] + "...")
Expected Output:
[87, 67, 75, 87, 90, 14, 20, 95, 14, 18, ...
Question 37: Decrypt JSON Backup (Mock)
Write a function import_decrypted(filepath, key) that loads the XOR integer list, applies the decrypting key, parses the JSON string, and returns the data dictionary.
main.pyRunnable## Solution def import_decrypted(filepath: str, key: int) -> dict: with open(filepath, "r", encoding="utf-8") as file: encrypted = json.load(file) decrypted_chars = [chr(val ^ key) for val in encrypted] json_str = "".join(decrypted_chars) return json.loads(json_str) ## Verification print(import_decrypted("db_crypt.json", 42))
Expected Output:
{'sku': 'A', 'stock': 5}
Question 38: Automatic Schema Version Validator
Write a validation method verify_schema(data) that ensures loaded JSON payload dictionaries contain specific required fields: ['items', 'version', 'timestamp'], raising a KeyError if any schema field is missing.
main.pyRunnable## Solution def verify_schema(data: dict): required = {"items", "version", "timestamp"} missing = required - set(data.keys()) if missing: raise KeyError(f"Missing schema attributes: {sorted(list(missing))}") ## Verification payload = {"items": [], "version": "1.0.0"} try: verify_schema(payload) except KeyError as e: print(e)
Expected Output:
"Missing schema attributes: ['timestamp']"
Question 39: Custom Text-file Data Export (CSV style)
Write a method export_csv(filepath) on your Warehouse class that writes a formatted CSV database (without external csv package dependency), using commas as splits.
main.pyRunnable## Solution class CSVWarehouse(Warehouse): def export_csv(self, filepath: str): with open(filepath, "w", encoding="utf-8") as file: file.write("sku,name,cost,quantity\n") for sku, item in self.catalog.items(): qty = getattr(item, 'quantity', 0) file.write(f"{sku},{item.name},{item.cost:.2f},{qty}\n") ## Verification w = CSVWarehouse() w.register_item("SEN-1", SerializedItemFactory("Sensor", 8.50, 12, 2)) w.export_csv("warehouse.csv") with open("warehouse.csv", "r") as file: print(file.read().strip())
Expected Output:
sku,name,cost,quantity SEN-1,Sensor,8.50,12
Question 40: CSV Database File Import
Write a method import_csv(filepath) on your Warehouse class that parses the text-based CSV dataset, populating your inventory collections catalog.
main.pyRunnable## Solution class FullCSVWarehouse(Warehouse): def import_csv(self, filepath: str): self.catalog.clear() with open(filepath, "r", encoding="utf-8") as file: lines = file.readlines() # Skip header for line in lines[1:]: stripped = line.strip() if not stripped: continue sku, name, cost_str, qty_str = stripped.split(",") self.catalog[sku] = SerializedItemFactory( name=name, cost=float(cost_str), quantity=int(qty_str), threshold=2 ) ## Verification w = FullCSVWarehouse() w.import_csv("warehouse.csv") print(f"Imported SKU: {w.get_item('SEN-1').name}, Stock: {w.get_item('SEN-1').quantity}")
Expected Output:
Imported SKU: Sensor, Stock: 12
Progress Check (Level 4)
Level 5: High-Performance Pipelines, Dynamic Context Managers & Advanced Orchestration (Questions 41–50)
Question 41: Atomic Database Write (Corruption Guard)
Write a helper function atomic_write_json(data, filepath) that prevents data corruption by writing to a temporary file (.tmp) first, and then atomically renaming it to the target file.
main.pyRunnable## Solution import os def atomic_write_json(data: dict, filepath: str): tmp_path = filepath + ".tmp" with open(tmp_path, "w", encoding="utf-8") as file: json.dump(data, file, indent=4) os.replace(tmp_path, filepath) ## Verification payload = {"inventory_state": "stable"} atomic_write_json(payload, "secure_vault.json") with open("secure_vault.json", "r") as file: print(file.read().strip())
Expected Output:
{ "inventory_state": "stable" }
Question 42: Transaction Rollback Context Manager
Implement a class-based context manager TransactionSession on Warehouse that yields a temporary copy of the inventory catalog. If any exception occurs inside the with block, changes are rolled back.
main.pyRunnable## Solution import copy class TransactionSession: def __init__(self, warehouse: Warehouse): self.warehouse = warehouse self._backup = None def __enter__(self): # Create deep copy backup self._backup = copy.deepcopy(self.warehouse.catalog) return self.warehouse def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is not None: # Exception raised, roll back catalog changes self.warehouse.catalog = self._backup print(f"[Transaction] Rolled back due to exception: {exc_val}") return False # propagation allowed print("[Transaction] Session committed successfully.") return True
- Verification Script:
main.pyRunnable## Verification w = Warehouse() i = InventoryItemThreshold("CPU", 200.0, 10, 2) w.register_item("CPU-9", i) try: with TransactionSession(w) as session: session.catalog["CPU-9"].quantity = 100 # Trigger an arbitrary exception raise RuntimeError("Operational system fault.") except RuntimeError: pass print(f"Post Rollback CPU Stock: {w.get_item('CPU-9').quantity}")
Expected Output:
[Transaction] Rolled back due to exception: Operational system fault. Post Rollback CPU Stock: 10
Question 43: High-Performance Reading Generator
Write a generator function read_corpus_chunks(filepath, chunk_size=1024) that streams big corpus text files in small chunk blocks rather than loading the whole file to memory.
main.pyRunnable## Solution def read_corpus_chunks(filepath: str, chunk_size: int = 1024): with open(filepath, "r", encoding="utf-8") as file: while True: chunk = file.read(chunk_size) if not chunk: break yield chunk ## Verification with open("stream_test.txt", "w", encoding="utf-8") as f: f.write("Line A\n" * 200) chunks = list(read_corpus_chunks("stream_test.txt", 128)) print(f"Read {len(chunks)} text chunks sequentially.")
Expected Output:
Read 11 text chunks sequentially.
Question 44: Custom Profiling Decorator
Write a decorator @profile_lexical_time that registers execution time and prints standard reports.
main.pyRunnable## Solution import time def profile_lexical_time(func): def wrapper(*args, **kwargs): t0 = time.perf_counter() result = func(*args, **kwargs) t1 = time.perf_counter() print(f"[Profiler] '{func.__name__}' completed execution in {t1-t0:f} seconds.") return result return wrapper ## Verification @profile_lexical_time def complex_pipeline(): total = sum(x**2 for x in range(100000)) return total print(f"Sum: {complex_pipeline()}")
Expected Output:
[Profiler] 'complex_pipeline' completed execution in ... seconds. Sum: 333328333350000
Question 45: Dynamic CLI Argument Dispatcher
Write a simple argument dispatcher class MiniDispatcher that matches string flags like --export or --import to specific callable class methods.
main.pyRunnable## Solution class MiniDispatcher: def __init__(self): self._actions = {} def register(self, flag: str, handler): self._actions[flag] = handler def dispatch(self, flag: str, *args): if flag in self._actions: self._actions[flag](*args) else: print(f"[Error] Action flag '{flag}' not recognized.") ## Verification disp = MiniDispatcher() disp.register("--status", lambda: print("System Catalog Stable")) disp.dispatch("--status")
Expected Output:
System Catalog Stable
Question 46: Complex Multi-threaded Task Runners (Standard Library)
Write a mock inventory worker pipeline using threading to update warehouse items concurrently in independent threads.
main.pyRunnable## Solution import threading def thread_replenish(item: InventoryItem, qty: int): item.quantity += qty ## Verification item = InventoryItemThreshold("Microphone", 40.0, 5, 2) threads = [] for _ in range(5): t = threading.Thread(target=thread_replenish, args=(item, 10)) threads.append(t) t.start() for t in threads: t.join() print(f"Final Microphones Count: {item.quantity}")
Expected Output:
Final Microphones Count: 55
Question 47: Read-Only Proxy Wrapper Pattern
Create a read-only class proxy wrapper ReadOnlyItemProxy that isolates class variables, raising an AttributeError if any attributes are modified or deleted.
main.pyRunnable## Solution class ReadOnlyItemProxy: def __init__(self, item: InventoryItem): super().__setattr__("_item", item) def __getattr__(self, name): return getattr(self._item, name) def __setattr__(self, name, value): raise AttributeError("Inventory asset record is locked and read-only.") ## Verification item = InventoryItem("Screen", 150.00) proxy = ReadOnlyItemProxy(item) print(f"Proxy read cost: ${proxy.cost:.2f}") try: proxy.cost = 10.00 except AttributeError as e: print(f"Proxy Blocked: {e}")
Expected Output:
Proxy read cost: $150.00 Proxy Blocked: Inventory asset record is locked and read-only.
Question 48: JSON Serialization Custom Encoder
Write a custom standard library JSON serializer function that serializes instances of InventoryItem using a fallback function in json.dump.
main.pyRunnable## Solution def item_encoder_fallback(obj): if isinstance(obj, InventoryItem): return { "__type__": "InventoryItem", "name": obj.name, "cost": obj.cost, "quantity": getattr(obj, "quantity", 0), "threshold": getattr(obj, "threshold", 0) } raise TypeError(f"Object of type {type(obj)} is not JSON serializable") ## Verification i = InventoryItemThreshold("FPGA Board", 120.00, 2, 1) raw_json = json.dumps(i, default=item_encoder_fallback, indent=2) print(raw_json)
Expected Output:
{ "__type__": "InventoryItem", "name": "FPGA Board", "cost": 120.0, "quantity": 2, "threshold": 1 }
Question 49: Self-documenting Class Decorator
Write a class-level decorator @add_timestamp that appends a dynamic class property metadata recording instantiation timestamps when warehouse items are built.
main.pyRunnable## Solution import datetime def add_timestamp(cls): orig_init = cls.__init__ def new_init(self, *args, **kwargs): orig_init(self, *args, **kwargs) self.metadata = {"timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")} cls.__init__ = new_init return cls ## Verification @add_timestamp class TimestampsItem(InventoryItem): pass item = TimestampsItem("Board", 15.00) print(f"Class Metadata Timestamp exists: {'timestamp' in item.metadata}")
Expected Output:
Class Metadata Timestamp exists: True
Question 50: Memory usage monitor (Mock Profiler)
Write a decorator @profile_memory_usage that monitors the size in bytes of local in-memory catalog databases.
main.pyRunnable## Solution import sys def profile_memory_usage(func): def wrapper(*args, **kwargs): result = func(*args, **kwargs) size = sys.getsizeof(result) print(f"[Profiler] Returned data object size: {size} bytes.") return result return wrapper ## Verification @profile_memory_usage def get_large_db(): return {str(x): x for x in range(500)} large_db = get_large_db()
Expected Output:
[Profiler] Returned data object size: ... bytes.
Progress Check (Level 5)
Finished this lesson?
Mark it complete to advance your curriculum progress.