Exercise Answers
Mutability Exercises
These exercises are all in the mutability.py file in the exercises directory. Edit the file to fix the error(s) in the function(s). To run the test: from the exercises folder, type python test.py <function_name>, like this:
$ python test.py swap_ends
Swap Ends
The following code is failing the tests. Figure out why the code is failing and then fix it:
def swap_ends(sequence):
"""Swap the first and last items in the given list."""
sequence = sequence[-1:] + sequence[1:-1] + sequence[:1]
It should work like this:
>>> from mutability import swap_ends
>>> numbers = [1, 2, 3, 4, 5]
>>> swap_ends(numbers)
>>> numbers
[5, 2, 3, 4, 1]
Answers
We need to modify the original list instead of reusing the same variable name.
def swap_ends(sequence):
"""Swap the first and last items in the given list."""
sequence[0], sequence[-1] = sequence[-1], sequence[0]
Rotate List
The following code is failing the tests. Figure out why the code is failing and then fix it:
def rotate_list(some_list):
"""Move first list item to end of list and return the item moved."""
some_list = some_list[1:] + some_list[:1]
return some_list[-1]
It should work like this:
>>> from mutability import rotate_list
>>> numbers = [1, 2, 3, 4, 5]
>>> rotate_list(numbers)
1
>>> numbers
[2, 3, 4, 5, 1]
>>>
Answers
We need to modify the original list instead of reusing the same variable name.
def rotate_list(some_list):
item = some_list.pop(0)
some_list.append(item)
return item
Pop N
The following code is failing the tests. Figure out why the code is failing and then fix it:
def pop_n(sequence, n):
"""Remove and return the last n items from the mutable sequence."""
ret = sequence[-n:]
sequence = sequence[:-n]
return ret
It should work like this:
>>> from mutability import pop_n
>>> numbers = [1, 2, 3, 4, 5]
>>> pop_n(numbers, 2)
[4, 5]
>>> numbers
[1, 2, 3]
>>> pop_n(numbers, 0)
[]
>>> numbers
[1, 2, 3]
>>> pop_n(numbers, 3)
[1, 2, 3]
>>> numbers
[]
Answers
Shadowing the int variable name makes the int built-in function not work.
def pop_n(sequence, n):
"""Remove and return the last n items from the mutable sequence."""
popped = []
for _ in range(n):
popped = [sequence.pop()] + popped
return popped
Sort Names
The following code is failing the tests. Figure out why the code is failing and then fix it:
def name_key(name):
"""Return last-first name tuple from first-last name string."""
first, last = name.split()
return last, first
def sort_names(names):
"""Return given first-last name strings sorted by last name."""
return names.sort(key=name_key)
The code should work like this:
>>> from mutability import sort_names
>>> names = ["Jill Moore", "Ben Sato", "Tanya Jackson", "Evelyn Moore"]
>>> sort_names(names)
['Tanya Jackson', 'Evelyn Moore', 'Jill Moore', 'Ben Sato']
Answers
def name_key(name):
"""Return last-first name tuple from first-last name string."""
first, last = name.split()
return last, first
def sort_names(names):
return sorted(names, key=name_key)
Extended Swap Ends
Modify swap_ends to accept an optional argument n that will specify how many elements from the beginning and end should be swapped.
>>> from mutability import swap_ends
>>> numbers = [1, 2, 3, 4, 5]
>>> swap_ends(numbers, n=2)
>>> numbers
[5, 4, 3, 2, 1]
>>> numbers = [1, 2, 3, 4, 5, 6, 7]
>>> swap_ends(numbers, n=2)
>>> numbers
[7, 6, 3, 4, 5, 2, 1]
Note
To test this exercise you’ll need to comment out the @unittest.expectedFailure line in mutability_test.py.
Answers
def swap_ends(sequence, n=1):
"""Swap the first and last items in the given list."""
for i in range(1, n+1):
sequence[i-1], sequence[-i] = sequence[-i], sequence[i-1]
Is Perfect Cube
The following code is failing the tests. Figure out why the code is failing and then fix it:
def is_perfect_cube(n):
"""Return True if the given number is a perfect cube."""
return round(n**(1/3)) ** 3 is n
It should work like this:
>>> from mutability import is_perfect_cube
>>> is_perfect_cube(64)
True
>>> is_perfect_cube(453)
False
>>> is_perfect_cube(2197) # 13**3
True
Answers
The is operator needs to be an == operator.
def is_perfect_cube(n):
"""Return True if the given number is a perfect cube."""
return round(n**(1/3)) ** 3 == n
Identity
The following code is failing the tests. Figure out why the code is failing and then fix it:
def identity(int):
"""Return an identity matrix of size int x int"""
return [
[int(row == col) for row in range(int)]
for col in range(int)
]
It should work like this:
>>> from mutability import identity
>>> identity(2)
[[1, 0], [0, 1]]
>>> identity(3)
[[1, 0, 0], [0, 1, 0], [0, 0, 1]]
>>> identity(4)
[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
Answers
Shadowing the int variable name makes the int built-in function not work.
def identity(size):
"""Return an identity matrix of size int x int"""
return [
[int(row == col) for row in range(size)]
for col in range(size)
]
Object Exercises
These exercises are all in the objects.py file in the exercises directory. Edit the file to fix the error(s) in the function(s). To run the test: from the exercises folder, type python test.py <function_name>, like this:
$ python test.py split_in_half
Split in Half
This code works, but it is a bit of a mess: it has lots of variables, which makes it cluttered and rather difficult to read. Clean up the code.
def split_in_half(sequence):
"""Return two halves of the given sequence."""
length = len(sequence)
half_way = length // 2
first_half = sequence[:half_way]
second_half = sequence[half_way:]
combined = (first_half, second_half)
return combined
It should work like this:
>>> from objects import split_in_half
>>> split_in_half([1, 2, 3, 4])
([1, 2], [3, 4])
>>> split_in_half([1, 2, 3, 4, 5])
([1, 2], [3, 4, 5])
>>> split_in_half([1, 2])
([1], [2])
>>> split_in_half([])
([], [])
>>> split_in_half([1])
([], [1])
Try your function on other iterables (strings or tuples). Does it still work?
>>> from objects import split_in_half
>>> split_in_half("Hello world!")
('Hello ', 'world!')
>>> split_in_half((1, 2))
((1,), (2,))
Answers
One Line:
def split_in_half(things):
"""Return two halves of the given iterable."""
return (things[:len(things) // 2], things[len(things) // 2:])
With Variable:
def split_in_half(things):
"""Return two halves of the given iterable."""
half_way = len(things) // 2
return things[:half_way], things[half_way:]
Vote Tally
Write a function get_vote_tally that takes a multi-line string where each line contains a name and numbers representing voted choices.
The function should return a list of tuples, where each tuple contains a vote count and the options chosen that had that vote count.
The returned list should be sorted in descending order of vote counts.
Here’s an example of how it should work:
>>> from objects import get_vote_tally
>>> get_vote_tally("Victor: 1 3 4\nPaul: 1 3\nAlex: 2 3 4\nMildred: 2 4\n")
[(3, [3, 4]), (2, [1, 2])]
That list of tuples represents the fact that options 3 and 4 each received 3 votes and options 1 and 2 each received 2 votes.
Here’s a broken implementation of this function. Figure out what’s broken and how to fix it.
from collections import Counter
import re
def get_vote_tally(text):
counts_to_choices = Counter(re.findall(r"\d+", text))
tally_groups = dict.fromkeys(counts_to_choices.values(), set())
for choice, count in counts_to_choices.most_common():
tally_groups[count].add(int(choice))
return [
(count, sorted(choices))
for count, choices in tally_groups.items()
]
Answers
from collections import Counter
import re
def get_vote_tally(text):
counts_to_choices = Counter(re.findall(r"\d+", text))
tally_groups = {}
for choice, count in counts_to_choices.most_common():
tally_groups.setdefault(count, set()).add(int(choice))
return [
(count, sorted(choices))
for count, choices in tally_groups.items()
]
Using a defaultdict:
from collections import defaultdict, Counter
import re
def get_vote_tally(text):
counts_to_choices = Counter(re.findall(r"\d+", text))
tally_groups = defaultdict(set)
for choice, count in counts_to_choices.most_common():
tally_groups[count].add(int(choice))
return [
(count, sorted(choices))
for count, choices in tally_groups.items()
]
Flavor
Here we have a class Flavor to represent flavors of ice cream.
Unfortunately, it does not pass the tests.
Refactor the class to make it pass the tests.
class Flavor:
"""Flavor of ice cream."""
def __init__(self, name, ingredients=[], has_dairy=True):
self.name = name
self.ingredients = ingredients
self.has_dairy = has_dairy
def __contains__(self, ingredient):
"""Return True if the given ingredient is in this flavor."""
return ingredient in self.ingredients
def __repr__(self):
return (
f"{type(self).__name__}(name={self.name!r},"
f" ingredients={self.ingredients},"
f" has_dairy={self.has_dairy})"
)
It should work like this:
>>> from objects import Flavor
>>> vanilla = Flavor("vanilla")
>>> vanilla.name
'vanilla'
>>> vanilla.has_dairy
True
>>> vanilla.ingredients
[]
>>> vanilla
Flavor(name='vanilla', ingredients=[], has_dairy=True)
>>> mint_chip = Flavor(
... name="mint chip",
... ingredients=["sugar", "mint", "cashews", "coconut milk"],
... has_dairy=False,
... )
>>> mint_chip.ingredients
['sugar', 'mint', 'cashews', 'coconut milk']
>>> mint_chip.has_dairy
False
Answers
class Flavor:
"""Flavor of ice cream."""
def __init__(self, name, ingredients=[], has_dairy=True):
self.name = name
self.ingredients = list(ingredients)
self.has_dairy = has_dairy
def __contains__(self, ingredient):
"""Return True if the given ingredient is in this flavor."""
return ingredient in self.ingredients
def __repr__(self):
return (
f"{type(self).__name__}(name={self.name!r},"
f" ingredients={self.ingredients},"
f" has_dairy={self.has_dairy})"
)
Function Exercises
These exercises are all in the functions.py file in the exercises directory. Edit the file to refactor the function(s) or fix the error(s) in the function(s). To run the test: from the exercises folder, type python test.py <function_name>, like this:
$ python test.py longest_first
longest_first
Here’s a function that sorts strings based on their lengths.
def longest_first(strings):
"""Return list of strings with longest first."""
length_and_string = [(len(s), s) for s in strings]
sorted_with_key = sorted(length_and_string, reverse=True)
return [t[1] for t in sorted_with_key]
It should work like this:
>>> from functions import longest_first
>>> # Some of us are lazy typers when we can be.
>>> strings = "We want the longest string".split()
>>> strings
['We', 'want', 'the', 'longest', 'string']
>>> longest_first(strings)
['longest', 'string', 'want', 'the', 'We']
>>> strings = "123 9 3949501 9999 345".split()
>>> strings
['123', '9', '3949501', '9999', '345']
>>> longest_first(strings)
['3949501', '9999', '123', '345', '9']
>>> longest_first([""])
['']
>>> longest_first(["string"])
['string']
Refactor this function to make it simpler.
Hint
This could all be one (fairly readable) line of code.
Answers
def longest_first(strings):
"""Return list of strings with longest first."""
return sorted(strings, key=len, reverse=True)
get_earliest
Here’s a function that accepts any number of date strings and returns the date string that represents the earliest date. Note we are using the US date format of “MM/DD/YYYY”; apologies to those of you who normally use other versions of date formats.
def get_earliest(*dates):
"""Return the earliest of all the entered dates."""
rearranged = []
for date in dates:
m, d, y = date.split("/")
rearranged.append((y, m, d))
y, m, d = min(rearranged)
return f"{m}/{d}/{y}"
This function can be used like this:
>>> from functions import get_earliest
>>> get_earliest('12/31/2023', '01/01/2024')
'12/31/2023'
>>> get_earliest('12/31/2023', '01/01/2024', '04/06/1999', '06/04/1999')
'04/06/1999'
Refactor this function to use the min function with a key argument instead.
Hint
Define a parse_date function that turns a date string into a (year, month, day) tuple and then pass that function to the min function’s key argument to find the date string that represents the earliest date.
Answers
def parse_date(date):
m, d, y = date.split('/')
return y, m, d
def get_earliest(*dates):
"""Return the earliest of all the entered dates."""
return min(dates, key=parse_date)
Four
Write a four decorator that ignores the function it’s decorating and returns the number 4 instead.
Note that the decorated function is replaced by the number 4 (it’s not even a function anymore).
This decorator is obviously ridiculous, but making it should reinforce your understanding of decorators.
>>> from functions import four
>>> @four
... def greet(name):
... print("Hello {}".format(name))
...
>>> greet
4
>>> type(greet)
<class 'int'>
Answers
def four(func):
"""Return 4 (ignore decorated function)."""
return 4
Groot
Write a groot decorator that ignores the function it’s decorating and returns a function that prints “Groot”.
Yes, this decorator is also ridiculous, but making it should reinforce your understanding of decorators.
>>> from functions import groot
>>> @groot
... def greet(name):
... print("Hello {}".format(name))
...
>>> greet("Trey")
Groot
Answers
from functools import wraps
def groot(func):
"""Return function which prints 'Groot' (ignore decoratee)."""
@wraps(func)
def new_func(*args, **kwargs):
print("Groot")
return new_func
JSONify
Make a decorator jsonify that will take the return value of the function and return a JSON-encoded version of the return value.
>>> from functions import jsonify
>>> @jsonify
... def get_thing():
... return {'trey': "red", 'diane': "purple"}
...
>>> get_thing()
'{"trey": "red", "diane": "purple"}'
Hint
You’ll want to use json.dumps
Answers
import json
from functools import wraps
def jsonify(func):
"""Return JSON-encoded value returned by decorated function."""
@wraps(func)
def new_func(*args, **kwargs):
return json.dumps(func(*args, **kwargs))
return new_func
Iterable Exercises
These exercises are all in the iterables.py file in the exercises directory. Edit the file to fix the error(s) in the function(s). To run the test: from the exercises folder, type python test.py <function_name>, like this:
$ python test.py parse_ranges
Starting with a vowel
The function get_vowel_names accepts a list of names and returns a new list containing all names that start with a vowel.
def get_vowel_names(names):
"""Return a list containing all names given that start with a vowel."""
vowel_names = []
for name in names:
if name[0].lower() in "aeiou":
vowel_names.append(name)
return vowel_names
Here’s an example usage:
>>> from iterables import get_vowel_names
>>> names = ["Alice", "Bob", "Christy", "Jules"]
>>> get_vowel_names(names)
['Alice']
>>> names = ["scott", "arthur", "jan", "elizabeth"]
>>> get_vowel_names(names)
['arthur', 'elizabeth']
Refactor this code to use a list comprehension. I recommend copy-pasting your way from a loop to a comprehension.
Answers
def get_vowel_names(names):
"""Return a list containing all names given that start with a vowel."""
return [
name
for name in names
if name[0].lower() in "aeiou"
]
Parse Ranges
The function parse_ranges takes a string containing (inclusive) ranges of numbers and returns an iterable of those numbers.
The numeric ranges in the string will consist of two numbers separated by hyphens and each of the ranges will be separated by commas and any number of spaces.
It works like this:
>>> from iterables import parse_ranges
>>> for n in parse_ranges('1-2,4-4,8-13'):
... print(n)
1
2
4
8
9
10
11
12
13
>>> print(*parse_ranges('0-0, 4-8, 20-20, 43-45'))
0 4 5 6 7 8 20 43 44 45
Here's a solution for this version.
def parse_ranges(ranges_string):
"""Return iterable based on comma-separated numeric ranges."""
pairs = [
group.split('-')
for group in ranges_string.split(',')
]
numbers = [
num
for start, stop in pairs
for num in range(int(start), int(stop)+1)
]
return numbers
Now refactor it so that it returns a lazy iterator.
It should work like this:
>>> from iterables import parse_ranges
>>> numbers = parse_ranges('1-2,4-4')
>>> next(numbers)
1
>>> next(numbers)
2
>>> next(numbers)
4
>>> next(numbers)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>
>>> numbers = parse_ranges('100-10000')
>>> next(numbers)
100
>>> next(numbers)
101
Answers
We’re currently returning a list by using a list comprehension. We could turn that list comprehension into a generator expression to return a generator instead:
def parse_ranges(ranges_string):
"""Return iterable based on comma-separated numeric ranges."""
pairs = (
group.split('-')
for group in ranges_string.split(',')
)
return (
num
for start, stop in pairs
for num in range(int(start), int(stop)+1)
)
Or we could go back to using a for loop and turn our function into a [generator function][] that yields values.
def parse_ranges(ranges_string):
"""Return iterable based on comma-separated numeric ranges."""
pairs = (
group.split('-')
for group in ranges_string.split(',')
)
for start, stop in pairs:
for num in range(int(start), int(stop)+1):
yield num
One more improvement to this solution: we can use yield from instead of just yield:
def parse_ranges(ranges_string):
"""Return iterable based on comma-separated numeric ranges."""
pairs = (
group.split('-')
for group in ranges_string.split(',')
)
for start, stop in pairs:
yield from range(int(start), int(stop)+1)
Whenever you see for x in iterable: yield x you can instead write yield from iterable.
Interleave
The function interleave accepts two iterables and returns a list with the items in each iterable “interleaved” (item 0 from iterable 1, then item 0 from iterable 2, then item 1 from iterable 1, and so on). Assume the two lists have the same length.
def interleave(*iterables):
"""Return iterable of one item at a time from each given iterable."""
interleaved = []
for i in range(len(iterables[0])):
for iterable in iterables:
interleaved.append(iterable[i])
return interleaved
Refactor this code so that it works with any iterable (not just lists and sequences).
Example:
>>> from iterables import interleave
>>> from itertools import count, islice
>>> squares = (n**2 for n in count())
>>> list(islice(interleave(count(), squares), 10))
[0, 0, 1, 1, 2, 4, 3, 9, 4, 16]
Answers
def interleave(*iterables):
"""Return list of one item at a time from each given iterable."""
interleaved = []
for group in zip(*iterables):
for item in group:
interleaved.append(item)
return interleaved
def interleave(*iterables):
"""Return list of one item at a time from each given iterable."""
return [
item
for group in zip(*iterables)
for item in group
]
Numeric Range
The numeric_range function accepts an iterable of numbers and computes their numeric range (the difference between the largest and smallest number).
The current implementation of this function does not work for any iterable:
def numeric_range(iterable):
"""Return difference between largest and smallest given numbers."""
return max(iterable) - min(iterable)
Refactor this function to work with any iterable.
>>> from iterables import numeric_range
>>> numeric_range([10, 8, 7, 5, 3, 6, 2])
8
>>> numeric_range({8, 7, 5, 3, 9, 6, 2})
7
>>> numeric_range(n**2 for n in range(4))
9
Answers
This works but if the iterable was very long, we’d make a very large list needlessly:
def numeric_range(iterable):
"""Return difference between largest and smallest given numbers."""
sequence = list(iterable)
return max(sequence) - min(sequence)
This is more memory efficient:
def numeric_range(iterable):
"""Return difference between largest and smallest given numbers."""
maximum = None
minimum = None
for n in iterable:
if maximum is None or maximum < n:
maximum = n
if minimum is None or n < minimum:
minimum = n
return maximum - minimum
This will work even for an empty iterable:
def numeric_range(iterable):
"""Return difference between largest and smallest given numbers."""
iterator = iter(iterable)
try:
minimum = maximum = next(iterator)
except StopIteration:
minimum = maximum = 0
for n in iterable:
if maximum < n:
maximum = n
if n < minimum:
minimum = n
return maximum - minimum
Infinite Interleave
Revisit interleave but make it work even with infinitely long iterables (the return value must be an iterator). To test this, comment out the @unittest.expectedFailure line in the iterables_test.py file, under class InterleaveTests.
Example:
>>> from iterables import interleave
>>> from itertools import count, islice
>>> squares = (n**2 for n in count())
>>> list(islice(interleave(count(), squares), 10))
[0, 0, 1, 1, 2, 4, 3, 9, 4, 16]
Answers
def interleave(*iterables):
"""Yield one item at a time from each given iterable."""
return (
item
for group in zip(*iterables)
for item in group
)
def interleave(*iterables):
"""Yield one item at a time from each given iterable."""
for group in zip(*iterables):
for item in group:
yield item
def interleave(*iterables):
"""Yield one item at a time from each given iterable."""
for group in zip(*iterables):
yield from group
Head
The head accepts an iterable and a number n and returns the first n items from the iterable.
Currently this function accepts sequences, but not other types of iterables:
So these work:
>>> from iterables import head
>>> numbers = [2, 1, 3, 4, 7, 11]
>>> for n in head(numbers, 3):
... print(n)
...
2
1
3
>>> "".join(head('hello', 2))
'he'
>>> list(head('hello', 0))
[]
But this doesn’t work:
>>> head(enumerate('hello'), 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in head
TypeError: 'enumerate' object is not subscriptable
Here’s the current implementation of this function:
def head(iterable, n):
"""Return the first n items of given iterable."""
return iterable[:n]
Answers
def head(iterable, n):
"""Return the first n items of given iterable."""
return (
item
for item, _ in zip(iterable, range(n))
)
With islice from the standard library module itertools:
from itertools import islice
def head(iterable, n):
"""Return the first n items of given iterable."""
return islice(iterable, n)
Class Exercises
These exercises are all in the classes.py file in the exercises directory.
Edit the file to refactor the class or fix the error(s) in the class.
To run the test: from the exercises folder, type python test.py <class_name>, like this:
$ python test.py Row
Row
Make a Row class that accepts any keyword arguments given to it and stores these arguments as attributes.
Hint
Note that ** can be used to capture all keyword arguments given to a function or method into a dictionary.
It should work like this:
>>> from classes import Row
>>> row = Row(a=1, b=2)
>>> row.a
1
>>> row.b
2
Answers
class Row:
"""Row class that stores all given arguments as attributes."""
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
def __repr__(self):
attrs = ", ".join(
f"{key}={value}"
for key, value in self.__dict__.items()
)
return f"{type(self).__name__}({attrs})"
Or using __dict__ to initialize and to get a nice string representation:
class Row:
"""Row class that stores all given arguments as attributes."""
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def __repr__(self):
attrs = ", ".join(
f"{key}={value}"
for key, value in self.__dict__.items()
)
return f"{type(self).__name__}({attrs})"
Make Class
For this exercise, make a friendly class factory function. This make_class function should accept a class name and a list of argument names and should return a class with an initializer and a nice string representation:
>>> from classes import make_class
>>> Point = make_class('Point', ['x', 'y'])
>>> p = Point(1, 2)
>>> p.x
1
>>> p
Point(x=1, y=2)
The arguments can be accepted positionally (as above) or as keyword arguments:
>>> from classes import make_class
>>> Point = make_class('Point', ['x', 'y'])
>>> q = Point(x=3, y=4)
>>> q
Point(x=3, y=4)
>>> q.y
4
A TypeError should be raised if any arguments are missing:
>>> from classes import make_class
>>> Point = make_class('Point', ['x', 'y'])
>>> Point(1)
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: __init__() missing 1 required positional argument: 'y'
A TypeError should also be raised if any extra/unknown arguments are given:
>>> from classes import make_class
>>> Point = make_class('Point', ['x', 'y'])
>>> Point(1, 2, 3)
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: __init__() takes 3 positional arguments but 4 were given
The argument names given to make_class must be valid Python variable names.
A ValueError should be raised otherwise:
>>> from classes import make_class
>>> make_class('Person', ['name', '1st_place'])
Traceback (most recent call last):
File "<string>", line 1, in <module>
ValueError: Invalid arguments: 1st_place
Arguments should also be accepted if given as a single string of valid argument names:
>>> from classes import make_class
>>> Person = make_class('Person', 'name favorite_color')
>>> Person("Trey", "purple")
Person(name='Trey', favorite_color='purple')
And if this class is inherited from, the string representation of child classes should show their class name instead:
>>> class ColorfulPoint(Point):
... def __init__(self, x, y, color):
... self.color = color
... super().__init__(x, y)
...
>>> p = ColorfulPoint(1, 2, 'purple')
>>> p.color
'purple'
>>> p
ColorfulPoint(x=1, y=2)
You might notice that this class creation helper is very similar to collections.namedtuple.
Answers
def make_class(name, arguments):
"""Class factory function."""
if isinstance(arguments, str):
arguments = arguments.split(" ")
if not all(a.isidentifier() for a in arguments):
raise ValueError("Invalid arguments")
def __init__(self, *args, **kwargs):
attrs = {}
for name, value in zip(arguments, args):
attrs[name] = value
if kwargs.keys() & attrs.keys():
raise TypeError("Multiple values for argument")
attrs.update(kwargs)
if len(args) > len(arguments) or attrs.keys() - set(arguments):
raise TypeError("Extra arguments")
if set(arguments) - attrs.keys():
raise TypeError("Missing arguments")
for name, value in attrs.items():
setattr(self, name, value)
def __repr__(self):
attrs = ", ".join(
f"{name}={getattr(self, name)!r}"
for name in arguments
)
return f"{type(self).__name__}({attrs})"
return type(name, (), {"__init__": __init__, "__repr__": __repr__})
Using dataclasses:
from dataclasses import dataclass
from typing import Any
def make_class(name, arguments):
"""Class factory function."""
if isinstance(arguments, str):
arguments = arguments.split(" ")
try:
return dataclass(type(name, (), {"__annotations__": {
arg: Any
for arg in arguments
}}))
except SyntaxError:
raise ValueError("Invalid argument name") from None
Using the dataclass helper function make_dataclass:
from dataclasses import make_dataclass
def make_class(name, arguments):
"""Class factory function."""
if isinstance(arguments, str):
arguments = arguments.split(" ")
try:
return make_dataclass(name, arguments)
except TypeError as e:
raise ValueError("Invalid argument name") from e
Easy Class
Make an easyclass decorator which makes a dataclass that is frozen and also iterable.
It should work like this:
>>> from classes import easyclass
>>> @easyclass
... class Vector:
... x: float
... y: float
... z: float
... color: str = "black"
...
>>> v = Vector(1, 2, 3, "purple")
>>> u = Vector(4, 5, 6)
>>> w = Vector(4, 5, 6)
>>> v
Vector(x=1, y=2, z=3, color='purple')
>>> w == u
True
Answers
import dataclasses
def easyclass(cls):
def __iter__(self):
for field in cls.__dataclass_fields__:
yield getattr(self, field)
cls.__iter__ = __iter__
cls = dataclasses.dataclass(frozen=True)(cls)
return cls
A slightly cleaner version:
import dataclasses
def easyclass(cls):
"""Decorator to make dataclass frozen and iterable."""
def __iter__(self):
for field in dataclasses.fields(cls):
yield getattr(self, field.name)
cls.__iter__ = __iter__
cls = dataclasses.dataclass(cls, frozen=True)
return cls
Auto Repr
Make a class decorator auto_repr which accepts args and kwargs arguments and adds an appropriate __repr__ method to the decorated class.
>>> from classes import auto_repr
>>> @auto_repr(args=['x', 'y'], kwargs=['color'])
... class Point:
... def __init__(self, x, y, color='purple'):
... self.x, self.y = x, y
... self.color = color
...
>>> Point(1, 2)
Point(1, 2, color='purple')
>>> Point(x=3, y=4, color='green')
Point(3, 4, color='green')
There is a helper function for you to use, make_repr, which accepts args and kwargs attributes and will return an appropriate __repr__ method for the class to which it is attached. The helper function format_arguments is another helper that is used by make_repr.
def format_arguments(*args, **kwargs):
arg_strings = (
repr(a)
for a in args
)
kwarg_strings = (
f"{name}={value!r}"
for name, value in kwargs.items()
)
return ", ".join([*arg_strings, *kwarg_strings])
def make_repr(args=(), kwargs=()):
"""Make a repr method for the class."""
def __repr__(self):
arg_values = [self.__dict__[a] for a in args]
kwarg_values = {a: self.__dict__[a] for a in kwargs}
arg_string = format_arguments(*arg_values, **kwarg_values)
return f"{type(self).__name__}({arg_string})"
return __repr__
It works like this:
>>> from classes import make_repr
>>> class Point:
... def __init__(self, x, y, color='purple'):
... self.x, self.y = x, y
... self.color = color
... __repr__ = make_repr(args=['x', 'y'], kwargs=['color'])
...
>>> Point(1, 2)
Point(1, 2, color='purple')
>>> Point(x=3, y=4, color='green')
Point(3, 4, color='green')
Answers
def auto_repr(*, args=(), kwargs=()):
"""Class decorator to automatically creat a __repr__."""
def decorator(cls):
cls.__repr__ = make_repr(args=args, kwargs=kwargs)
return cls
return decorator
Protocol Exercises
These exercises are all in the protocols.py file in the exercises directory. Edit the file to fix the error(s) in the function(s). To run the test: from the exercises folder, type python test.py <function_name>, like this:
$ python test.py swap_ends
X marks the spot
The following code is failing the tests. Figure out why the code is failing and then fix it:
def words_containing(words, letter):
"""Return all words that contain the given letter."""
matching_words = []
for word in words:
if letter in word.lower():
matching_words += word
return matching_words
The code should work like this:
>>> from protocols import words_containing
>>> words_containing(['My', 'life', 'is', 'my', 'message'], 'y')
['My', 'my']
>>> words_containing(['My', 'life', 'is', 'my', 'message'], 'i')
['life', 'is']
>>> words_containing(['My', 'life', 'is', 'my', 'message'], 'm')
['My', 'my', 'message']
Answers
def words_containing(words, letter):
matching_words = []
for word in words:
if letter in word.lower():
matching_words.append(word)
return matching_words
Convert from CSV Data
The from_csv accepts a string of CSV data and converts it into a list of lists.
It works like this:
>>> from protocols import from_csv
>>> text = 'purple,0.15\ncrimson red,0.30\nindigo,0.25\nsky blue,0.05\nspring green,0.25\n'
>>> from_csv(text)
[['purple', '0.15'], ['crimson red', '0.30'], ['indigo', '0.25'], ['sky blue', '0.05'], ['spring green', '0.25']]
>>> from_csv('purple,0.15')
[['purple', '0.15']]
>>> from_csv('')
[]
The current implementation of this function uses a temporary file to store the CSV data:
import csv
from tempfile import NamedTemporaryFile
def from_csv(csv_data):
"""Convert string of CSV data to list of lists"""
with NamedTemporaryFile(mode="wt+") as csv_file:
csv_file.write(csv_data)
csv_file.seek(0)
return list(csv.reader(csv_file))
Refactor this function so that it doesn’t use a temporary file.
Answers
import csv
def from_csv(csv_data):
"""Convert string of CSV data to list of lists"""
return list(csv.reader(csv_data.splitlines()))
Convert to CSV Data
The to_csv function accepts an iterable-of-iterables and converts it into a string of CSV data.
It works like this:
>>> from protocols import to_csv
>>> iterable_data = [['purple', '0.15'], ['crimson red', '0.30'], ['indigo', '0.25'], ['sky blue', '0.05'], ['spring green', '0.25']]
>>> to_csv(iterable_data)
'purple,0.15\r\ncrimson red,0.30\r\nindigo,0.25\r\nsky blue,0.05\r\nspring green,0.25\r\n'
The current implementation of this function uses a temporary file to store the CSV data:
import csv
def to_csv(rows):
"""Convert iterable-of-iterables to string of CSV data"""
with NamedTemporaryFile(mode="wt+") as csv_file:
writer = csv.writer(csv_file)
writer.writerows(rows)
csv_file.seek(0)
return csv_file.read()
Refactor this function so that it doesn’t use a temporary file.
Answers
import csv
import io
def to_csv(rows):
"""Convert iterable-of-iterables to string of CSV data"""
csv_file = io.StringIO()
csv.writer(csv_file).writerows(rows)
return csv_file.getvalue()
Sum Timestamps
The sum_timestamps function takes a list of timestamp strings of “minute:seconds”, and returns a “minute:seconds” timestamp string that represents the total time from the list of timestamps.
>>> from protocols import sum_timestamps
>>> times = ["1:10", "0:12", "4:03", "2:45"]
>>> sum_timestamps(times)
'8:10'
>>> times = ["0:55", "0:55", "0:55", "0:55", "0:55"]
>>> sum_timestamps(times)
'4:35'
>>> sum_timestamps(["0:00"])
'0:00'
Here’s the current implementation of sum_timestamps, which uses parse_time and format_time helper functions:
def parse_time(time_string):
"""Return total seconds from string of minutes:seconds."""
sections = time_string.split(':')
return int(sections[0]) * 60 + int(sections[1])
def format_time(seconds):
"""Return a minutes:seconds string based on input seconds."""
sections = divmod(seconds, 60)
return f"{sections[0]}:{sections[1]:02d}"
def sum_timestamps(timestamps):
"""Return a timestamp that represents the sum of the input timestamps."""
total_seconds = [
parse_time(time)
for time in timestamps
]
return format_time(sum(total_seconds))
Refactor the sum_timestamps function so that it doesn’t require a temporary list.
Hint
Use a generator expression.
Answers
def sum_timestamps(timestamps):
"""Return a timestamp that represents the sum of the input timestamps."""
total_seconds = (
parse_time(time)
for time in timestamps
)
return format_time(sum(total_seconds))
def sum_timestamps(timestamps):
"""Return a timestamp that represents the sum of the input timestamps."""
return format_time(sum(
parse_time(time)
for time in timestamps
))