Project 2 · Practice

Quiz & exercises

Answer each question to see the explanation. Your best score is saved in this browser.

Quiz

1. Why can the lazy properties of Polygon cache their values without ever needing to reset them?
2. What does this print?
class Square:
    def __init__(self, side):
        self._side = side
        self._area = None

    @property
    def area(self):
        if self._area is None:
            print('computing')
            self._area = self._side ** 2
        return self._area

sq = Square(3)
print(sq.area + sq.area)
3. What does this print?
class Shapes:
    def __init__(self, m):
        self._m = m
        self._i = 3
    def __iter__(self):
        return self
    def __next__(self):
        if self._i > self._m:
            raise StopIteration
        self._i += 1
        return self._i - 1

s = Shapes(5)
print(list(s), len(list(s)))
4. In the refactored Polygons, why does __iter__ return PolygonsIterator(self._m, self._R) instead of self?
5. What does this print?
polygons = iter(['tri', 'square', 'pentagon'])
best = max(polygons, key=len)
print(best, list(polygons))
6. The lazy Polygons(m, R) stores no polygons. How can len() still work?
7. What does this print?
from functools import cached_property

class Hexagon:
    @cached_property
    def area(self):
        print('computing')
        return 42

h = Hexagon()
h.area
h.area
print('area' in vars(h))

Coding exercises

Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.

Exercise 1: Goal 1: lazy Polygon properties

Refactor the Polygon class so that every calculated property (interior_angle, side_length, apothem, area, perimeter) is lazy:

- nothing is calculated when a Polygon is created - each value is calculated on first access and cached - later accesses return the cached value without recalculating

Validation (n < 3 raises ValueError), the repr, equality and ordering must keep working exactly as before.

The tests check results and laziness: they count how often math.sin and math.cos are called.

Hints (3)
  1. In __init__, add a backing attribute per calculated property, e.g. self._area = None.
  2. In each property: if self._area is None: self._area = ... and then return self._area.
  3. Let area and perimeter use the side_length and apothem properties, so they reuse the cached values.
Show a solution
import math

class Polygon:
    def __init__(self, n, R):
        if n < 3:
            raise ValueError('Polygon must have at least 3 vertices.')
        self._n = n
        self._R = R
        self._interior_angle = None
        self._side_length = None
        self._apothem = None
        self._area = None
        self._perimeter = None

    def __repr__(self):
        return f'Polygon(n={self._n}, R={self._R})'

    @property
    def count_vertices(self):
        return self._n

    @property
    def count_edges(self):
        return self._n

    @property
    def circumradius(self):
        return self._R

    @property
    def interior_angle(self):
        if self._interior_angle is None:
            self._interior_angle = (self._n - 2) * 180 / self._n
        return self._interior_angle

    @property
    def side_length(self):
        if self._side_length is None:
            self._side_length = 2 * self._R * math.sin(math.pi / self._n)
        return self._side_length

    @property
    def apothem(self):
        if self._apothem is None:
            self._apothem = self._R * math.cos(math.pi / self._n)
        return self._apothem

    @property
    def area(self):
        if self._area is None:
            self._area = self._n / 2 * self.side_length * self.apothem
        return self._area

    @property
    def perimeter(self):
        if self._perimeter is None:
            self._perimeter = self._n * self.side_length
        return self._perimeter

    def __eq__(self, other):
        if isinstance(other, self.__class__):
            return (self.count_edges == other.count_edges
                    and self.circumradius == other.circumradius)
        return NotImplemented

    def __gt__(self, other):
        if isinstance(other, self.__class__):
            return self.count_vertices > other.count_vertices
        return NotImplemented

Exercise 2: Goal 2: Polygons as a lazy iterable

Polygons(m, R) is currently a sequence that builds a list of every polygon up front. Refactor it into an iterable:

- write an iterator class PolygonsIterator(m, R) that returns Polygon(3, R), Polygon(4, R), …, Polygon(m, R) and then raises StopIteration; it must create each polygon only when next() is called - Polygons.__iter__ must return a new PolygonsIterator every time - Polygons must not create or store any polygons itself - keep len() (which is m - 2), the repr, and the ValueError for m < 3

The lazy Polygon class from Goal 1 is provided. (max_efficiency_polygon is the next exercise.)

Hints (3)
  1. PolygonsIterator needs _m, _R and a counter _i starting at 3. __next__ raises StopIteration once _i > _m.
  2. Create the Polygon inside __next__, not in __init__.
  3. In Polygons, delete the list and __getitem__, and add def __iter__(self): return PolygonsIterator(self._m, self._R).
Show a solution
import math

class Polygon:
    def __init__(self, n, R):
        if n < 3:
            raise ValueError('Polygon must have at least 3 vertices.')
        self._n = n
        self._R = R
        self._interior_angle = None
        self._side_length = None
        self._apothem = None
        self._area = None
        self._perimeter = None

    def __repr__(self):
        return f'Polygon(n={self._n}, R={self._R})'

    @property
    def count_vertices(self):
        return self._n

    @property
    def count_edges(self):
        return self._n

    @property
    def circumradius(self):
        return self._R

    @property
    def interior_angle(self):
        if self._interior_angle is None:
            self._interior_angle = (self._n - 2) * 180 / self._n
        return self._interior_angle

    @property
    def side_length(self):
        if self._side_length is None:
            self._side_length = 2 * self._R * math.sin(math.pi / self._n)
        return self._side_length

    @property
    def apothem(self):
        if self._apothem is None:
            self._apothem = self._R * math.cos(math.pi / self._n)
        return self._apothem

    @property
    def area(self):
        if self._area is None:
            self._area = self._n / 2 * self.side_length * self.apothem
        return self._area

    @property
    def perimeter(self):
        if self._perimeter is None:
            self._perimeter = self._n * self.side_length
        return self._perimeter

    def __eq__(self, other):
        if isinstance(other, self.__class__):
            return (self.count_edges == other.count_edges
                    and self.circumradius == other.circumradius)
        return NotImplemented

    def __gt__(self, other):
        if isinstance(other, self.__class__):
            return self.count_vertices > other.count_vertices
        return NotImplemented


class PolygonsIterator:
    def __init__(self, m, R):
        if m < 3:
            raise ValueError('m must be greater than 3')
        self._m = m
        self._R = R
        self._i = 3

    def __iter__(self):
        return self

    def __next__(self):
        if self._i > self._m:
            raise StopIteration
        result = Polygon(self._i, self._R)
        self._i += 1
        return result


class Polygons:
    def __init__(self, m, R):
        if m < 3:
            raise ValueError('m must be greater than 3')
        self._m = m
        self._R = R

    def __len__(self):
        return self._m - 2

    def __repr__(self):
        return f'Polygons(m={self._m}, R={self._R})'

    def __iter__(self):
        return PolygonsIterator(self._m, self._R)

Exercise 3: Goal 2: a lazy max_efficiency_polygon

Polygons is now a lazy iterable, but its max_efficiency_polygon property still iterates over every polygon each time it's read.

Make it a lazy property: compute the polygon with the highest area / perimeter ratio on the first access only, cache it, and return the cached polygon afterwards. Creating a Polygons object must still not create any polygons.

Hints (3)
  1. Add self._max_efficiency_polygon = None in __init__.
  2. In the property, compute only if self._max_efficiency_polygon is None.
  3. max(self, key=lambda p: p.area / p.perimeter) finds the best polygon in one pass, because self is iterable.
Show a solution
import math

class Polygon:
    def __init__(self, n, R):
        if n < 3:
            raise ValueError('Polygon must have at least 3 vertices.')
        self._n = n
        self._R = R
        self._interior_angle = None
        self._side_length = None
        self._apothem = None
        self._area = None
        self._perimeter = None

    def __repr__(self):
        return f'Polygon(n={self._n}, R={self._R})'

    @property
    def count_vertices(self):
        return self._n

    @property
    def count_edges(self):
        return self._n

    @property
    def circumradius(self):
        return self._R

    @property
    def interior_angle(self):
        if self._interior_angle is None:
            self._interior_angle = (self._n - 2) * 180 / self._n
        return self._interior_angle

    @property
    def side_length(self):
        if self._side_length is None:
            self._side_length = 2 * self._R * math.sin(math.pi / self._n)
        return self._side_length

    @property
    def apothem(self):
        if self._apothem is None:
            self._apothem = self._R * math.cos(math.pi / self._n)
        return self._apothem

    @property
    def area(self):
        if self._area is None:
            self._area = self._n / 2 * self.side_length * self.apothem
        return self._area

    @property
    def perimeter(self):
        if self._perimeter is None:
            self._perimeter = self._n * self.side_length
        return self._perimeter

    def __eq__(self, other):
        if isinstance(other, self.__class__):
            return (self.count_edges == other.count_edges
                    and self.circumradius == other.circumradius)
        return NotImplemented

    def __gt__(self, other):
        if isinstance(other, self.__class__):
            return self.count_vertices > other.count_vertices
        return NotImplemented


class PolygonsIterator:
    def __init__(self, m, R):
        if m < 3:
            raise ValueError('m must be greater than 3')
        self._m = m
        self._R = R
        self._i = 3

    def __iter__(self):
        return self

    def __next__(self):
        if self._i > self._m:
            raise StopIteration
        result = Polygon(self._i, self._R)
        self._i += 1
        return result


class Polygons:
    def __init__(self, m, R):
        if m < 3:
            raise ValueError('m must be greater than 3')
        self._m = m
        self._R = R
        self._max_efficiency_polygon = None

    def __len__(self):
        return self._m - 2

    def __repr__(self):
        return f'Polygons(m={self._m}, R={self._R})'

    def __iter__(self):
        return PolygonsIterator(self._m, self._R)

    @property
    def max_efficiency_polygon(self):
        if self._max_efficiency_polygon is None:
            self._max_efficiency_polygon = max(
                self, key=lambda p: p.area / p.perimeter)
        return self._max_efficiency_polygon