Lecture 18 Finger Exercise
Please Log In for full access to the web site.
Note that this link will take you to an external site (https://shimmer.mit.edu) to authenticate, and then you will be redirected back to this page.
For both questions in this finger exercise, you may assume the following classes or equivalent are available to use. You may use any of the methods shown, but you may not directly access any of the data attributes.
class Point:
"""A Point is a location in two-dimensional Euclidean space."""
def __init__(self, x, y):
"""
Initialize a Point at numeric x- and y-coordinates (given as ints or floats).
Once initialized, a Point should not change location.
"""
self.x = x
self.y = y
def __str__(self):
return f"<{self.x}, {self.y}>"
def __eq__(self, other):
"""Two Points are identical if they have the same x- and y-coordinates."""
return self.x == other.x and self.y == other.y
def get_x(self):
return self.x
def get_y(self):
return self.y
def get_distance(self, other):
"""Return the magnitude of the distance between two Points."""
dx = self.x - other.x
dy = self.y - other.y
return (dx ** 2 + dy ** 2) ** 0.5
class Plane:
"""A Plane stores a set of unique Points."""
def __init__(self):
"""Initialize a Plane with no Points."""
self.points = []
def add_point(self, point):
"""Store a Point in this Plane."""
if point not in self.points:
self.points.append(point)
def get_points(self):
"""Return a list containing all the Points stored in this Plane."""
return self.points.copy()
For example, suppose the following code is run: Then, farthest_point(plane) function that meets the specification below.
def farthest_point(plane):
"""
Given a Plane, return a Point stored within it that is farthest from
the origin. If multiple Points are equally far away from the origin,
return any one of them. If there are no Points in the Plane, return None.
"""
x_vals = (-2, -1, 0, 1, 2)
y_vals = (0, 1)
flatland = Plane()
for x in x_vals:
for y in y_vals:
flatland.add_point(Point(x, y))
farthest_point(flatland) should evaluate to either "<-2, 1>" or "<2, 1>".
For example, consider defining the following. Then, Polygon according to the specifications below.
class Polygon:
"""
A Polygon is a two-dimensional shape formed by connecting three or
more Points in sequence.
"""
def __init__(self, vertices):
"""
Initialize a Polygon given a list of Points as vertices.
The edges are implied to be line segments connecting adjacent
Points in vertices, with the last Point also being connected to
the first.
Once initialized, a Polygon's vertices should be fixed.
"""
def get_num_edges(self):
"""Return the number of edges for a Polygon."""
def get_perimeter(self):
"""Return the total length of all of a Polygon's edges."""
v1 = Point(0, 0)
v2 = Point(3, 0)
v3 = Point(3, 4)
triangle = Polygon([v1, v2, v3])
triangle.get_num_edges() should evaluate to 3, and triangle.get_perimeter() should evaluate to 12.0.