Guide Python Intermediate

12.20 Hands-on Exercises

Practice programs reinforcing Python set concepts -- a duplicate remover, a unique-visitor counter built on len(set(...)), and a package comparator reporting missing and extra entries via set difference.

2 min read

Duplicate Remover

def remove_duplicates(items):
    return list(set(items))

>>> sorted(remove_duplicates([1, 1, 2, 3, 3]))
[1, 2, 3]

Unique Visitor Counter

Counting distinct visitors from a raw log of (possibly repeated) visitor IDs.

def unique_visitors(visitor_log):
    return len(set(visitor_log))

>>> unique_visitors(["u1", "u2", "u1", "u3"])
3

Package Comparator

Reporting missing and extra packages between an installed set and a required set — the same pattern as 12.16 Sets in DevOps.

def compare_packages(installed, required):
    installed_set, required_set = set(installed), set(required)
    return {
        "missing": required_set - installed_set,
        "extra": installed_set - required_set,
    }

>>> compare_packages(["nginx", "redis"], ["nginx", "postgres"])
{'missing': {'postgres'}, 'extra': {'redis'}}

Quick Interview Answer

“These three exercises build up from the simplest set use case to a realistic infrastructure pattern: remove_duplicates is list(set(...)) in its most basic form, unique_visitors shows that counting distinct items is just len() applied to a set instead of the raw log, and compare_packages combines two differences — required - installed and installed - required — into a single dict report, the exact shape a package-audit or inventory script needs in practice.”

Common Mistakes

  • Returning set(items) from remove_duplicates when a list was the expected return type — wrap with list(...) to match the original type.
  • Computing unique_visitors by manually looping and tracking a seen list with in checks, instead of the direct len(set(...)) one-liner.
  • Building compare_packages with only one direction of difference, silently missing either the “missing” or “extra” half of the comparison.

Add More Questions to This Guide

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

Open Google Form