Python Updates · Practice
Quiz & exercises
Answer each question to see the explanation. Your best score is saved in this browser.
Quiz
Coding exercises
Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.
Exercise 1: A command interpreter with match ✓ Passed
Write run(command) that takes a list of words and uses a match statement to return:
- ["add", a, b] → the sum of the two numbers, e.g. run(["add", "2", "3"]) returns 5 (convert with int) - ["echo", *words] → the words joined with single spaces, e.g. run(["echo", "hi", "there"]) returns 'hi there' - ["quit"] or ["exit"] → the string 'bye' - anything else → raise ValueError
def run(command):
# use match/case here
pass
def test_add():
"""add sums two numbers"""
assert run(["add", "2", "3"]) == 5, f"got {run(['add', '2', '3'])!r}"
def test_echo():
"""echo joins the remaining words"""
assert run(["echo", "hi", "there"]) == "hi there"
assert run(["echo"]) == "", "echo with no words should return ''"
def test_quit_exit():
"""quit and exit both return 'bye'"""
assert run(["quit"]) == "bye" and run(["exit"]) == "bye"
def test_unknown():
"""unknown commands raise ValueError"""
for bad in (["fly"], ["add", "1"], ["quit", "now"], []):
try:
run(bad)
except ValueError:
continue
raise AssertionError(f"{bad!r} should raise ValueError")
Hints (3)
- A pattern like
["add", a, b]only matches a sequence of exactly three items, binding the last two. - Use
*wordsto collect any number of remaining items, and|to combine["quit"]and["exit"]in one case. - The wildcard
_catches everything else; raise the error there.
Show a solution
def run(command):
match command:
case ["add", a, b]:
return int(a) + int(b)
case ["echo", *words]:
return " ".join(words)
case ["quit"] | ["exit"]:
return "bye"
case _:
raise ValueError(f"unknown command: {command!r}")Exercise 2: Compute once, filter, keep ✓ Passed
normalize(s) is an "expensive" function. Write long_words(words, min_len) that returns a list of the normalized versions of the words whose normalized length is at least min_len, in the original order.
Call normalize exactly once per word. A list comprehension with := is the neat way to do it.
calls = 0
def normalize(s):
global calls
calls += 1
return s.strip().lower()
def long_words(words, min_len):
return [normalize(w) for w in words if len(normalize(w)) >= min_len]
def test_result():
"""returns the normalized long words in order"""
result = long_words([" Apple ", "fig", "BANANA", " kiwi"], 5)
assert result == ["apple", "banana"], f"got {result!r}"
def test_calls_once_per_word():
"""normalize is called exactly once per word"""
global calls
calls = 0
long_words([" Apple ", "fig", "BANANA", " kiwi"], 5)
assert calls == 4, f"normalize was called {calls} times for 4 words"
def test_empty():
"""an empty input gives an empty list"""
assert long_words([], 3) == []
Hints (2)
- The starter calls
normalizetwice for every word that passes the test. - The
ifclause runs before the output expression, so do the assignment there:if len(n := normalize(w)) >= min_len.
Show a solution
calls = 0
def normalize(s):
global calls
calls += 1
return s.strip().lower()
def long_words(words, min_len):
return [n for w in words if len(n := normalize(w)) >= min_len]Exercise 3: A named tuple factory from kwargs ✓ Passed
Write make_record(class_name, **fields) that returns a named tuple class whose field names are the keyword names in the order given, and whose default values are the keyword values.
For example, Point = make_record('Point', x=0, y=0, label='') should allow Point(5) to produce Point(x=5, y=0, label='').
from collections import namedtuple
def make_record(class_name, **fields):
return namedtuple(class_name, sorted(fields))
def test_field_order():
"""fields follow the keyword order"""
Point = make_record('Point', x=0, y=0, label='')
assert Point._fields == ('x', 'y', 'label'), f"got {Point._fields}"
def test_defaults():
"""all fields have the given defaults"""
Point = make_record('Point', x=0, y=0, label='')
assert Point() == (0, 0, ''), f"got {Point()!r}"
assert Point(5) == (5, 0, ''), f"got {Point(5)!r}"
def test_name():
"""the class gets the requested name"""
Rec = make_record('Rec', a=1)
assert Rec.__name__ == 'Rec' and repr(Rec()) == 'Rec(a=1)'
Hints (2)
- Since Python 3.6,
fieldskeeps the caller's order, so don't sort it. namedtupleaccepts adefaults=argument (3.7+). Alternatively setStruct.__new__.__defaults__ = tuple(fields.values()).
Show a solution
from collections import namedtuple
def make_record(class_name, **fields):
return namedtuple(class_name, fields.keys(), defaults=fields.values())