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.
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_duplicatesislist(set(...))in its most basic form,unique_visitorsshows that counting distinct items is justlen()applied to a set instead of the raw log, andcompare_packagescombines two differences —required - installedandinstalled - required— into a single dict report, the exact shape a package-audit or inventory script needs in practice.”
Common Mistakes
- Returning
set(items)fromremove_duplicateswhen alistwas the expected return type — wrap withlist(...)to match the original type. - Computing
unique_visitorsby manually looping and tracking aseenlist withinchecks, instead of the directlen(set(...))one-liner. - Building
compare_packageswith 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