Skip to content
Foxipa
Code Completion 4 Challenges

Complete the collections.Counter code

Practice counting iterable items, adding counts, preserving subtracted counts, and intersecting multisets.

Intermediate ~9 min read

Challenge 1

Build a Counter that tallies each item in the provided list.

python Your answer
from collections import Counter

colors = ["red", "blue", "red", "green"]
counts = 
print(counts["red"])
print(counts.most_common(1))

Press Ctrl⌘Enter to check your answer

Challenge 2

Add the supplied incoming counts to the Counter without replacing existing totals.

python Your answer
from collections import Counter

counts = Counter(apples=2, pears=1)

print(counts)

Press Ctrl⌘Enter to check your answer

Challenge 3

Subtract the shipment and keep the resulting negative stock count for pears.

python Your answer
from collections import Counter

stock = Counter(pears=1, apples=4)

print(stock["pears"])
print("pears" in stock)

Press Ctrl⌘Enter to check your answer

Challenge 4

Keep the minimum positive count for each item shared by these counters.

python Your answer
from collections import Counter

left = Counter(red=4, blue=1)
right = Counter(red=2, blue=3)
shared = 
print(shared)

Press Ctrl⌘Enter to check your answer