Project 1 · Practice

Quiz & exercises

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

Quiz

1. Why do the tests use math.isclose(p.side_length, math.sqrt(2), ...) instead of p.side_length == math.sqrt(2)?
2. Polygon defines __gt__ but not __lt__. What happens when you evaluate Polygon(3, 1) < Polygon(5, 1)?
3. What does this print?
class P:
    def __init__(self, n):
        self._n = n
    def __eq__(self, other):
        if isinstance(other, P):
            return self._n == other._n
        return NotImplemented

print(P(3) == P(3), P(3) == 3, P(3) != 'x')
4. What happens when this code runs?
class Circle:
    def __init__(self, r):
        self._r = r
    @property
    def radius(self):
        return self._r

c = Circle(1)
c.radius = 5
5. Polygons.__getitem__ simply returns self._polygons[s]. Which of these does that not give you automatically?
6. What does this print?
words = ['kiwi', 'banana', 'fig', 'cherry']
print(max(words, key=len), sorted(words, key=len, reverse=True)[0])
7. With a fixed circumradius R, which polygon in Polygons(m, R) has the highest area-to-perimeter ratio?

Coding exercises

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

Exercise 1: Goal 1a: Polygon properties

Create a class Polygon(n, R) for a regular convex polygon with n vertices and circumradius R.

- Raise ValueError if n < 3. - repr(Polygon(3, 1)) must be 'Polygon(n=3, R=1)'. - Provide these read-only properties (assigning to them must raise AttributeError): count_vertices, count_edges, circumradius, interior_angle (degrees), side_length, apothem, area, perimeter.

Formulas: interior angle (n - 2) * 180 / n; side 2 R sin(π/n); apothem R cos(π/n); area n / 2 * side * apothem; perimeter n * side.

Hints (3)
  1. Decorate each method with @property. A property with no setter is automatically read-only.
  2. Build area and perimeter from side_length and apothem so each formula appears only once.
  3. math.pi, math.sin and math.cos work in radians.
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

    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):
        return (self._n - 2) * 180 / self._n

    @property
    def side_length(self):
        return 2 * self._R * math.sin(math.pi / self._n)

    @property
    def apothem(self):
        return self._R * math.cos(math.pi / self._n)

    @property
    def area(self):
        return self._n / 2 * self.side_length * self.apothem

    @property
    def perimeter(self):
        return self._n * self.side_length

Exercise 2: Goal 1b: Equality and ordering

The starter contains a working Polygon class. Add comparisons:

- ==: two polygons are equal when they have the same number of vertices and the same circumradius. Comparing with a non-Polygon must not raise; it should simply be unequal. - > and <: based on the number of vertices only. Comparing with a non-Polygon using > or < should raise TypeError.

Implement as few methods as you can: Python's reflected comparisons will do the rest.

Hints (2)
  1. Return NotImplemented (don't raise) when other isn't a Polygon. Python turns that into False for == and a TypeError for >.
  2. __gt__ is enough for both > and <: for a < b Python tries b.__gt__(a). And != is derived from __eq__.
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

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

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

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

    @property
    def area(self):
        s = 2 * self._R * math.sin(math.pi / self._n)
        return self._n / 2 * s * self._R * math.cos(math.pi / self._n)

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

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

Exercise 3: Goal 2: The Polygons sequence

The starter includes the finished Polygon class. Write Polygons(m, R), an immutable sequence of the polygons with 3, 4, ..., m vertices, all with circumradius R.

- Raise ValueError if m < 3. - len() returns the number of polygons (m - 2). - Support indexing (positive and negative, IndexError when out of range), slicing including extended slices, and iteration. - repr(Polygons(6, 1)) is 'Polygons(m=6, R=1)'. - A read-only property max_efficiency_polygon returns the polygon with the highest area / perimeter ratio.

Hints (2)
  1. Build the polygons once in __init__ and keep them in a tuple. Then __getitem__ can just return self._polygons[s], which handles ints, negative indices, slices and IndexError.
  2. max(iterable, key=...) finds the item with the largest key in one pass.
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

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

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

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

    @property
    def side_length(self):
        return 2 * self._R * math.sin(math.pi / self._n)

    @property
    def apothem(self):
        return self._R * math.cos(math.pi / self._n)

    @property
    def area(self):
        return self._n / 2 * self.side_length * self.apothem

    @property
    def perimeter(self):
        return self._n * self.side_length

    def __eq__(self, other):
        if isinstance(other, Polygon):
            return (self._n, self._R) == (other._n, other._R)
        return NotImplemented

    def __gt__(self, other):
        if isinstance(other, Polygon):
            return self._n > other._n
        return NotImplemented


class Polygons:
    def __init__(self, m, R):
        if m < 3:
            raise ValueError('m must be at least 3')
        self._m = m
        self._R = R
        self._polygons = tuple(Polygon(n, R) for n in range(3, m + 1))

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

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

    def __getitem__(self, s):
        return self._polygons[s]

    @property
    def max_efficiency_polygon(self):
        return max(self._polygons, key=lambda p: p.area / p.perimeter)