from collections import Counter
# Count elements automatically
words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']
counts = Counter(words)
print(counts) # Counter({'apple': 3, 'banana': 2, 'cherry': 1})
# Most common elements
print(counts.most_common(2)) # [('apple', 3), ('banana', 2)]
# Math operations on counters
c1 = Counter(a=3, b=1)
c2 = Counter(a=1, b=2)
print(c1 + c2) # Counter({'a': 4, 'b': 3})
print(c1 - c2) # Counter({'a': 2}) (ignores zero/negative)from collections import defaultdict
# Auto-initializes missing keys!
# Normal dict would throw KeyError
groups = defaultdict(list)
groups['fruits'].append('apple') # Creates empty list automatically!
groups['fruits'].append('banana')
int_dict = defaultdict(int) # Default value 0
int_dict['count'] += 1
# Grouping pattern
students = [('A', 85), ('B', 92), ('A', 78), ('B', 88)]
by_grade = defaultdict(list)
for name, score in students:
by_grade[name].append(score)
# defaultdict(list, {'A': [85, 78], 'B': [92, 88]})from collections import deque
# O(1) append and pop from BOTH ends
dq = deque([1, 2, 3])
dq.append(4) # Add to right: [1, 2, 3, 4]
dq.appendleft(0) # Add to left: [0, 1, 2, 3, 4]
dq.pop() # Remove from right: returns 4
dq.popleft() # Remove from left: returns 0
# Rotate
dq = deque([1, 2, 3, 4, 5])
dq.rotate(2) # Rotate right 2: [4, 5, 1, 2, 3]
dq.rotate(-1) # Rotate left 1: [5, 1, 2, 3, 4]
# Fixed size (automatically discards from opposite end)
last_3 = deque(maxlen=3)
for i in range(5):
last_3.append(i)
print(last_3) # deque([2, 3, 4], maxlen=3)from collections import namedtuple
# Create a lightweight class
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
# Access by name (more readable than tuples!)
print(p.x) # 10
print(p[1]) # 20 (still supports index)
# Has _make, _asdict methods
coords = [30, 40]
p2 = Point._make(coords)
print(p2._asdict()) # {'x': 30, 'y': 40}from collections import ChainMap
# Group multiple dicts, searches in order
defaults = {'color': 'red', 'size': 'M'}
user_prefs = {'color': 'blue'}
combined = ChainMap(user_prefs, defaults)
print(combined['color']) # 'blue' (from user_prefs)
print(combined['size']) # 'M' (from defaults, not in user_prefs)Create a function `top_n_words(text, n)` that takes a string, splits it into words (case-insensitive, ignore punctuation), and returns the top N most frequent words using Counter. Create a function `moving_average(data, window_size)` that returns a list of moving averages using a `deque` with `maxlen` or manual window.