Exercises
The collections Module
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Print the two most common letters in the word, using Counter.
Python
# import Counter and print the top two of "mississippi"
most_common(2) gives them in order.
from collections import Counter
print(Counter("mississippi").most_common(2))Exercise 2Passed
Use a defaultdict so no key check is needed.
Python
from collections import defaultdict
pairs = [("maths", "ada"), ("maths", "grace")]
groups = {}
for subject, name in pairs:
groups[subject].append(name)
print(dict(groups))defaultdict takes a factory, such as list.
from collections import defaultdict
pairs = [("maths", "ada"), ("maths", "grace")]
groups = defaultdict(list)
for subject, name in pairs:
groups[subject].append(name)
print(dict(groups))Exercise 3Passed
Keep only the last three readings, using a deque that discards the rest for you.
Python
from collections import deque
last_three = deque()
for n in range(6):
last_three.append(n)
print(list(last_three))deque takes a maxlen.
from collections import deque
last_three = deque(maxlen=3)
for n in range(6):
last_three.append(n)
print(list(last_three))