Extras · 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 repeatable card deal ✓ Passed
Write deal(n, seed=None) that returns a list of n different cards from the 52-card deck DECK.
Requirements: the same seed must always produce the same hand, no card may appear twice, and asking for more than 52 cards must raise ValueError.
import random
suits = 'CDHS'
ranks = [str(r) for r in range(2, 11)] + list('JQKA')
DECK = [rank + suit for suit in suits for rank in ranks]
def deal(n, seed=None):
return random.choices(DECK, k=n)
def test_size():
"""returns n cards from the deck"""
hand = deal(5, seed=1)
assert len(hand) == 5, f"expected 5 cards, got {len(hand)}"
assert all(card in DECK for card in hand), "hand contains a card not in DECK"
def test_no_duplicates():
"""never deals the same card twice"""
for seed in range(50):
hand = deal(20, seed=seed)
assert len(set(hand)) == 20, f"duplicate cards with seed={seed}: {hand}"
def test_repeatable():
"""the same seed gives the same hand"""
assert deal(7, seed=123) == deal(7, seed=123)
def test_different_seeds():
"""different seeds usually give different hands"""
hands = {tuple(deal(5, seed=s)) for s in range(10)}
assert len(hands) > 1, "every seed produced the same hand"
def test_whole_deck():
"""dealing 52 cards gives the whole deck"""
assert sorted(deal(52, seed=0)) == sorted(DECK)
def test_too_many():
"""more than 52 cards raises ValueError"""
try:
deal(53, seed=0)
except ValueError:
return
assert False, "expected ValueError for 53 cards"
Hints (3)
choicespicks with replacement. Which function picks without replacement?- Seed the generator at the start of the function so each call with the same seed starts from the same state.
random.samplealready raisesValueErrorwhenkis larger than the population.
Show a solution
import random
suits = 'CDHS'
ranks = [str(r) for r in range(2, 11)] + list('JQKA')
DECK = [rank + suit for suit in suits for rank in ranks]
def deal(n, seed=None):
random.seed(seed)
return random.sample(DECK, k=n)Exercise 2: A lookup that allows None as a default ✓ Passed
Write lookup(mapping, key, default=...) that returns mapping[key] if the key exists.
If the key is missing: return default if the caller passed one (even if it is None), otherwise raise KeyError(key).
Use a private sentinel object, not None, as the parameter's default.
def lookup(mapping, key, default=None):
if key in mapping:
return mapping[key]
if default is None:
raise KeyError(key)
return default
def test_found():
"""returns the value when the key exists"""
assert lookup({'a': 1}, 'a') == 1
assert lookup({'a': None}, 'a', 'x') is None
def test_missing_no_default():
"""raises KeyError when the key is missing and no default is given"""
try:
lookup({'a': 1}, 'b')
except KeyError:
return
assert False, "expected KeyError"
def test_explicit_none_default():
"""an explicit default of None is returned, not treated as missing"""
result = 'not returned'
try:
result = lookup({'a': 1}, 'b', None)
except KeyError:
assert False, "lookup(..., None) raised KeyError: None should count as a real default"
assert result is None, f"expected None, got {result!r}"
def test_other_defaults():
"""falsy defaults like 0 and '' are returned too"""
assert lookup({}, 'x', 0) == 0
assert lookup({}, 'x', '') == ''
Hints (2)
- Create a unique object at module level, for example
_sentinel = object(), and make it the default. - Compare with
is:if default is _sentinel:is true only when the caller passed nothing.
Show a solution
_sentinel = object()
def lookup(mapping, key, default=_sentinel):
if key in mapping:
return mapping[key]
if default is _sentinel:
raise KeyError(key)
return defaultExercise 3: A command line greeter ✓ Passed
Write greet(argv) that parses the list argv with argparse and returns a list of greeting lines.
The interface: a required positional name; an option -t/--times (an int, default 1) giving how many lines to return; and a flag --shout that upper-cases the greeting. Each line is 'Hello, <name>!'.
Invalid input (such as -t abc or a missing name) should behave like any argparse error and raise SystemExit.
import argparse
def greet(argv):
parser = argparse.ArgumentParser(prog='greet.py')
parser.add_argument('name')
args = parser.parse_args(argv)
return [f'Hello, {args.name}!']
def test_basic():
"""one greeting by default"""
assert greet(['Ada']) == ['Hello, Ada!'], f"got {greet(['Ada'])!r}"
def test_times():
"""--times / -t repeats the greeting"""
assert greet(['Ada', '--times', '3']) == ['Hello, Ada!'] * 3
assert greet(['-t', '2', 'Bob']) == ['Hello, Bob!'] * 2
def test_shout():
"""--shout upper-cases the greeting"""
assert greet(['Ada', '--shout']) == ['HELLO, ADA!']
def test_bad_times():
"""a non-integer --times is rejected with SystemExit"""
try:
greet(['Ada', '-t', 'abc'])
except SystemExit as ex:
assert ex.code == 2, f"expected exit code 2, got {ex.code}"
return
assert False, "expected SystemExit for -t abc"
Hints (3)
add_argument('-t', '--times', type=int, default=1)gives youargs.timesas an integer.- A flag with no value uses
action='store_true'. [line] * nbuilds a list withncopies ofline.
Show a solution
import argparse
def greet(argv):
parser = argparse.ArgumentParser(prog='greet.py', description='Greets someone.')
parser.add_argument('name', help='who to greet')
parser.add_argument('-t', '--times', type=int, default=1, help='number of greetings')
parser.add_argument('--shout', action='store_true', help='use capital letters')
args = parser.parse_args(argv)
line = f'Hello, {args.name}!'
if args.shout:
line = line.upper()
return [line] * args.times