Guide Python Intermediate

12.21 Mini Projects

Four small set-based projects -- a duplicate log analyzer, an inventory comparator, a firewall rule comparator built on symmetric_difference(), and a unique host tracker -- applying the chapter's patterns to realistic infrastructure code.

2 min read

Duplicate Log Analyzer

def analyze_duplicate_logs(lines):
    seen, dups = set(), set()
    for l in lines:
        if l in seen:
            dups.add(l)
        seen.add(l)
    return dups

>>> analyze_duplicate_logs(["a", "b", "a"])
{'a'}

Inventory Comparator

def compare_inventory(current, expected):
    c, e = set(current), set(expected)
    return {"missing": e - c, "extra": c - e}

>>> compare_inventory(["web01", "web02"], ["web01", "web03"])
{'missing': {'web03'}, 'extra': {'web02'}}

Firewall Rule Comparator

Symmetric difference is exactly the right tool for finding rules that differ between two rule sets, regardless of direction (see 12.7 Set Operators).

def compare_firewall_rules(rules_a, rules_b):
    return set(rules_a).symmetric_difference(set(rules_b))

>>> compare_firewall_rules(["22", "80"], ["80", "443"])
{'22', '443'}

Unique Host Tracker

def track_unique_hosts(connections):
    return set(connections)

>>> track_unique_hosts(["host1", "host2", "host1"])
{'host1', 'host2'}

Quick Interview Answer

“Each mini project applies one set operation to a realistic infrastructure task: a running seen set flags exact-repeat log lines as they’re scanned; two differences run in both directions turn a current and expected server list into a missing/extra report; symmetric_difference() finds every firewall rule that differs between two rule sets without needing to run the comparison twice in each direction; and a unique host tracker is set() doing its single most basic job — collapsing a connection log down to the distinct hosts involved.”

Common Mistakes

  • Implementing analyze_duplicate_logs by counting occurrences with a dict when only whether a line repeats is needed — the seen/dups two-set pattern is simpler and communicates intent more directly.
  • Reporting only expected - current (or only current - expected) from compare_inventory — a complete audit needs both directions.
  • Reaching for two separate differences (rules_a - rules_b and rules_b - rules_a) to find what differs between two rule sets, when a single symmetric_difference() call does the same thing in one step.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form