Sequences · 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: Split a sequence into chunks ✓ Passed
Write chunked(seq, size) that splits any sequence into consecutive pieces of length size (the last piece may be shorter) and returns them as a list.
Each piece must have the same type as seq: chunking a string gives strings, chunking a tuple gives tuples. If size is less than 1, raise ValueError.
python chunked('abcdefg', 3) # ['abc', 'def', 'g'] chunked((1, 2, 3, 4), 2) # [(1, 2), (3, 4)] chunked([], 2) # []
def chunked(seq, size):
# your code here
pass
def test_string():
"""chunks a string into strings"""
assert chunked('abcdefg', 3) == ['abc', 'def', 'g'], chunked('abcdefg', 3)
def test_tuple():
"""chunks a tuple into tuples"""
assert chunked((1, 2, 3, 4), 2) == [(1, 2), (3, 4)]
def test_list_type():
"""chunks of a list are lists"""
result = chunked([1, 2, 3, 4, 5], 2)
assert result == [[1, 2], [3, 4], [5]], result
assert all(type(c) is list for c in result)
def test_range():
"""works with ranges too (slicing a range gives a range)"""
result = chunked(range(5), 2)
assert result == [range(0, 2), range(2, 4), range(4, 5)], result
def test_empty_and_large():
"""empty input, and size larger than the sequence"""
assert chunked([], 2) == []
assert chunked('ab', 10) == ['ab']
def test_bad_size():
"""size < 1 raises ValueError"""
try:
chunked('abc', 0)
except ValueError:
return
assert False, 'expected ValueError'
Hints (2)
- Slicing always returns the same type as the sequence being sliced, and out-of-range bounds are clipped.
range(0, len(seq), size)gives the start index of every chunk.
Show a solution
def chunked(seq, size):
if size < 1:
raise ValueError('size must be at least 1')
return [seq[i:i + size] for i in range(0, len(seq), size)]Exercise 2: A grid without aliases ✓ Passed
make_grid(rows, cols, fill) should return a list of rows lists, each containing cols copies of fill. The current version has a classic bug: changing one cell changes a whole column.
Fix it so that every row is an independent list.
def make_grid(rows, cols, fill=0):
return [[fill] * cols] * rows
def test_shape():
"""has the right shape and values"""
assert make_grid(2, 3) == [[0, 0, 0], [0, 0, 0]]
assert make_grid(1, 2, 'x') == [['x', 'x']]
def test_rows_independent():
"""rows are distinct objects"""
g = make_grid(3, 2)
assert g[0] is not g[1] and g[1] is not g[2], 'rows are the same list object'
def test_mutation():
"""changing one cell changes only that cell"""
g = make_grid(3, 3)
g[0][0] = 99
assert g == [[99, 0, 0], [0, 0, 0], [0, 0, 0]], g
def test_empty():
"""zero rows gives an empty list"""
assert make_grid(0, 5) == []
Hints (2)
[row] * rowsrepeats a reference to one row. You need a new row object for each repetition.- A list comprehension evaluates its expression once per iteration, creating a fresh list each time.
Show a solution
def make_grid(rows, cols, fill=0):
return [[fill] * cols for _ in range(rows)]Exercise 3: A lazy sequence of squares ✓ Passed
Write a class Squares(n) that behaves like the read-only sequence 0, 1, 4, 9, ..., (n-1)**2 without storing the values.
It must support:
- len(sq) returning n - indexing with positive and negative integers, raising IndexError when out of range - slicing (including steps and negative steps), returning a list of squares - iteration, in and reversed() (these follow automatically if the above is right)
class Squares:
def __init__(self, n):
self._n = n
def __len__(self):
return self._n
def __getitem__(self, s):
# your code here (s is an int or a slice)
raise IndexError('not implemented yet')
def test_len():
"""len() works"""
assert len(Squares(5)) == 5
def test_index():
"""positive and negative indexing"""
sq = Squares(5)
assert (sq[0], sq[3], sq[-1], sq[-5]) == (0, 9, 16, 0)
def test_index_error():
"""out-of-range indices raise IndexError"""
sq = Squares(5)
for bad in (5, 100, -6):
try:
sq[bad]
except IndexError:
continue
assert False, f'sq[{bad}] should raise IndexError'
def test_iteration():
"""iteration stops at the end"""
assert list(Squares(5)) == [0, 1, 4, 9, 16]
assert 9 in Squares(5) and 25 not in Squares(5)
def test_slices():
"""slices return lists, honoring steps"""
sq = Squares(6)
assert sq[1:4] == [1, 4, 9], sq[1:4]
assert sq[::2] == [0, 4, 16]
assert sq[::-1] == [25, 16, 9, 4, 1, 0]
assert sq[-2:] == [16, 25]
assert sq[10:20] == []
def test_reversed():
"""reversed() works"""
assert list(reversed(Squares(4))) == [9, 4, 1, 0]
Hints (2)
- Check
isinstance(s, slice)first.range(*s.indices(len(self)))gives exactly the positions the slice selects. - For an integer, add
nto a negative index, then raiseIndexErrorif it's still outside0 .. n-1. Without that, iteration never stops.
Show a solution
class Squares:
def __init__(self, n):
self._n = n
def __len__(self):
return self._n
def __getitem__(self, s):
if isinstance(s, slice):
return [i ** 2 for i in range(*s.indices(self._n))]
if s < 0:
s += self._n
if s < 0 or s >= self._n:
raise IndexError('Squares index out of range')
return s ** 2Exercise 4: Sort by several criteria ✓ Passed
Each record is a tuple (name, department, salary). Write sort_staff(records) that returns a new list ordered:
1. by department, alphabetically; 2. within a department, by salary, highest first; 3. when salaries tie too, by name, alphabetically.
The input must not be modified (it might be a tuple, or a list someone else is using).
def sort_staff(records):
records.sort()
return records
DATA = [
('Eve', 'ops', 50),
('Bob', 'dev', 70),
('Amy', 'dev', 90),
('Dan', 'ops', 50),
('Cid', 'dev', 70),
]
def test_order():
"""department, then salary descending, then name"""
expected = [
('Amy', 'dev', 90),
('Bob', 'dev', 70),
('Cid', 'dev', 70),
('Dan', 'ops', 50),
('Eve', 'ops', 50),
]
result = sort_staff(list(DATA))
assert result == expected, result
def test_not_mutated():
"""the input list is left unchanged"""
data = list(DATA)
sort_staff(data)
assert data == DATA, f'input was changed to {data}'
def test_tuple_input():
"""accepts a tuple and returns a list"""
result = sort_staff(tuple(DATA))
assert isinstance(result, list) and result[0] == ('Amy', 'dev', 90)
def test_empty():
"""empty input"""
assert sort_staff([]) == []
Hints (2)
sorted()accepts any iterable and returns a new list;list.sort()mutates (and tuples don't have it).- A key that returns a tuple sorts by its first element, then the second, and so on. Negate the salary to make just that part descending.
Show a solution
def sort_staff(records):
return sorted(records, key=lambda r: (r[1], -r[2], r[0]))