Lesson 14 of 15
Standard Library
Standard Library
Python's standard library is vast. A few essential modules:
collections
Counter counts hashable objects:
from collections import Counter
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
c = Counter(words)
c["apple"] # 3
c.most_common(2) # [('apple', 3), ('banana', 2)]
defaultdict returns a default value for missing keys:
from collections import defaultdict
groups = defaultdict(list)
groups["a"].append(1) # no KeyError
itertools
from itertools import chain, groupby, product, combinations
list(chain([1, 2], [3, 4])) # [1, 2, 3, 4]
list(combinations("ABC", 2)) # [('A','B'), ('A','C'), ('B','C')]
list(product([0,1], repeat=2)) # [(0,0), (0,1), (1,0), (1,1)]
functools
from functools import reduce, lru_cache
reduce(lambda a, b: a + b, [1, 2, 3, 4]) # 10
@lru_cache(maxsize=None)
def fib(n):
if n < 2: return n
return fib(n-1) + fib(n-2)
The @lru_cache line is a decorator — the @ syntax wraps fib so that its return values are cached. After the first call to fib(10), subsequent calls with the same argument return instantly from the cache instead of recomputing.
Your Task
Implement most_common_words(text, n) that:
- Splits
textinto words (by spaces), lowercases all words - Returns a list of the
nmost common words as(word, count)tuples, sorted by frequency (most frequent first)
Use collections.Counter.
Pyodide loading...
Loading...
Click "Run" to execute your code.