Power Tools: Sets & Counting Dicts
Power Tools: Sets & Counting Dicts 🧰
Remember counting unique words with a seen-list and a nested loop? You earned that sweat — and now you earn the reward. This unit hands you two power tools that turn yesterday's hardest problems into three-liners.
The set: a bag that refuses repeats
album = set()
album.add("star")
album.add("star") # bounces off!
len(album) # 1
Make one from any list with set(items). Ask membership with in — instantly, no loop. And sets know friendship tricks:
a & b # in both
a | b # in either
a - b # in a but not b
a <= b # is a completely inside b?
The dict as a tally counter
You know dicts. Here's their superpower — THE counting line:
counts = {}
for item in items:
counts[item] = counts.get(item, 0) + 1
.get(key, 0) reads a count that might not exist yet. With a tally dict plus your trusty best-so-far loop, you can crown winners, spot loners, and balance candy economies.
Several problems here are TURBO versions of puzzles you've already solved the slow way. Same puzzle, new tool — feel how much lighter it gets. That feeling is why tools exist. ⚡