A Quick Refresher · 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: Find the first negative ✓ Passed
Write first_negative(numbers) that returns the index of the first negative number in the list numbers, or -1 if there is none.
Use a for loop with enumerate, break, and the loop's else clause (no index() calls and no flag variable).
def first_negative(numbers):
result = -1
for value in numbers:
if value < 0:
result = value
return result
def test_found():
"""finds the index of the first negative number"""
assert first_negative([3, 1, -4, 1, -5]) == 2, f"got {first_negative([3, 1, -4, 1, -5])}"
def test_first_position():
"""works when the first item is negative"""
assert first_negative([-1, 2]) == 0, f"got {first_negative([-1, 2])}"
def test_none():
"""returns -1 when there is no negative number"""
assert first_negative([1, 2, 3]) == -1, f"got {first_negative([1, 2, 3])}"
def test_empty():
"""returns -1 for an empty list"""
assert first_negative([]) == -1, f"got {first_negative([])}"
Hints (2)
for i, value in enumerate(numbers):gives you the index and the value together.- Stop with
breakas soon as you find a negative. The loop'selseblock runs only if you never broke out, which is exactly the "not found" case.
Show a solution
def first_negative(numbers):
for i, value in enumerate(numbers):
if value < 0:
result = i
break
else:
result = -1
return resultExercise 2: Ratios without crashing ✓ Passed
Write safe_ratios(pairs) that takes a list of (a, b) tuples and returns a tuple (results, attempts):
- results is a list of a / b for every pair where the division works; pairs with b == 0 are skipped (use try / except ZeroDivisionError and continue). - attempts counts every pair processed, including skipped ones. Increment it in a finally block.
def safe_ratios(pairs):
results = []
attempts = 0
for a, b in pairs:
results.append(a / b)
attempts += 1
return results, attempts
def test_basic():
"""divides every pair when there are no zeros"""
assert safe_ratios([(1, 2), (9, 3)]) == ([0.5, 3.0], 2)
def test_skips_zero():
"""skips pairs that divide by zero"""
results, _ = safe_ratios([(1, 0), (4, 2), (5, 0)])
assert results == [2.0], f"got {results}"
def test_counts_all():
"""counts skipped pairs as attempts too"""
_, attempts = safe_ratios([(1, 0), (4, 2), (5, 0)])
assert attempts == 3, f"got {attempts}"
def test_empty():
"""handles an empty list"""
assert safe_ratios([]) == ([], 0)
Hints (2)
- Unpack each pair directly in the loop:
for a, b in pairs:. continuein theexceptblock skips theappend, but thefinallyblock still runs first, so the counter is always incremented.
Show a solution
def safe_ratios(pairs):
results = []
attempts = 0
for a, b in pairs:
try:
ratio = a / b
except ZeroDivisionError:
continue
finally:
attempts += 1
results.append(ratio)
return results, attemptsExercise 3: A small Money class ✓ Passed
Write a class Money whose instances hold an amount (in cents, an int):
- Money(250) creates an instance; repr() gives 'Money(250)' and str() gives '$2.50'. - amount is a property: setting it to a negative value raises ValueError, **including in __init__**. - == compares amounts, and < compares amounts too. Comparing with a non-Money object should return NotImplemented from your methods (so Money(1) == 1 is simply False).
class Money:
def __init__(self, amount):
self.amount = amount
def test_repr_str():
"""repr is Money(250), str is $2.50"""
m = Money(250)
assert repr(m) == 'Money(250)', f"repr was {repr(m)!r}"
assert str(m) == '$2.50', f"str was {str(m)!r}"
def test_str_padding():
"""str pads cents to two digits"""
assert str(Money(5)) == '$0.05', f"got {str(Money(5))!r}"
def test_equality():
"""equal amounts compare equal; other types don't"""
assert Money(100) == Money(100)
assert Money(100) != Money(99)
assert not (Money(1) == 1)
def test_ordering():
"""< and > compare amounts"""
assert Money(1) < Money(2)
assert Money(3) > Money(2)
def test_setter_validates():
"""setting a negative amount raises ValueError"""
m = Money(10)
try:
m.amount = -1
except ValueError:
pass
else:
assert False, "no ValueError for a negative amount"
assert m.amount == 10
def test_init_validates():
"""creating Money with a negative amount raises ValueError"""
try:
Money(-5)
except ValueError:
return
assert False, "Money(-5) did not raise ValueError"
Hints (3)
- Store the value in
self._amountand expose it with@property/@amount.setter. In__init__, assignself.amountso the setter validates it. - For
str,divmodor//and%split cents into dollars and cents;:02dpads to two digits. - You only need
__lt__: Python answersa > bby tryingb < a.
Show a solution
class Money:
def __init__(self, amount):
self.amount = amount # goes through the setter
@property
def amount(self):
return self._amount
@amount.setter
def amount(self, value):
if value < 0:
raise ValueError('amount must not be negative')
self._amount = value
def __repr__(self):
return f'Money({self.amount})'
def __str__(self):
return f'${self.amount // 100}.{self.amount % 100:02d}'
def __eq__(self, other):
if isinstance(other, Money):
return self.amount == other.amount
return NotImplemented
def __lt__(self, other):
if isinstance(other, Money):
return self.amount < other.amount
return NotImplementedExercise 4: Word frequencies ✓ Passed
Write word_counts(text) that returns a dict mapping each word in text to the number of times it appears.
- Words are separated by whitespace (use str.split() with no argument). - Counting is case-insensitive: convert words to lower case. - Strip the punctuation characters .,!? from both ends of each word, and skip words that end up empty.
Use a plain dict with get (no collections.Counter).
def word_counts(text):
counts = {}
for word in text.split(' '):
counts[word] = 1
return counts
def test_basic():
"""counts repeated words"""
assert word_counts('a b a') == {'a': 2, 'b': 1}, f"got {word_counts('a b a')}"
def test_case():
"""ignores case"""
assert word_counts('The the THE') == {'the': 3}, f"got {word_counts('The the THE')}"
def test_punctuation():
"""strips .,!? from the ends of words"""
result = word_counts('Hi, hi! Bye.')
assert result == {'hi': 2, 'bye': 1}, f"got {result}"
def test_whitespace():
"""handles runs of whitespace and skips empty words"""
result = word_counts(' one\ttwo one ! ')
assert result == {'one': 2, 'two': 1}, f"got {result}"
def test_empty():
"""returns an empty dict for empty text"""
assert word_counts('') == {}, f"got {word_counts('')}"
Hints (3)
text.split()with no argument splits on any whitespace and never produces empty strings.word.strip('.,!?')removes any of those characters from both ends.counts[word] = counts.get(word, 0) + 1handles both new and existing words.
Show a solution
def word_counts(text):
counts = {}
for word in text.split():
word = word.strip('.,!?').lower()
if word:
counts[word] = counts.get(word, 0) + 1
return countsExercise 5: Unique items, original order ✓ Passed
Write unique_in_order(items) that returns a list of the items in items with duplicates removed, keeping the position of each item's first appearance.
Use a set to remember what you've already seen (so each membership test is fast), and don't modify items.
def unique_in_order(items):
return list(set(items))
def test_order_kept():
"""keeps first-appearance order"""
result = unique_in_order([3, 1, 3, 2, 1])
assert result == [3, 1, 2], f"got {result}"
def test_strings():
"""works with strings"""
result = unique_in_order(['pear', 'apple', 'pear', 'fig', 'apple'])
assert result == ['pear', 'apple', 'fig'], f"got {result}"
def test_input_unchanged():
"""does not modify the input list"""
data = [2, 2, 1]
unique_in_order(data)
assert data == [2, 2, 1], f"input became {data}"
def test_returns_list():
"""returns a list, also for an empty input"""
assert unique_in_order([]) == []
assert isinstance(unique_in_order((1, 1)), list)
Hints (2)
- A set has no order, so
list(set(items))loses the original positions. - Loop over
items, and append an item to the result only if it isn't in aseenset yet; then add it toseen.
Show a solution
def unique_in_order(items):
seen = set()
result = []
for item in items:
if item not in seen:
seen.add(item)
result.append(item)
return result