Middle+
Python task: determine if there is a vertical axis of symmetry for a given list of points on the plane.
sobes.tech AI
Answer from AI
To determine whether a vertical axis of symmetry exists for a given list of points on a plane, you need to check if a vertical line can be drawn such that all points are symmetric with respect to it.
Solution idea:
- Find the minimum and maximum x-values among the points.
- Calculate the potential axis of symmetry as
axis = (min_x + max_x) / 2. - For each point, check if there exists a point with a mirrored coordinate relative to the axis: if the point is
(x, y), then there should be a point(2*axis - x, y).
Python code example:
from collections import defaultdict
def has_vertical_symmetry(points):
points_set = set(points)
xs = [x for x, y in points]
min_x, max_x = min(xs), max(xs)
axis = (min_x + max_x) / 2
for x, y in points:
mirrored = (2*axis - x, y)
if mirrored not in points_set:
return False
return True
# Example usage
points = [(1,1), (3,1), (2,2)]
print(has_vertical_symmetry(points)) # False
points = [(1,1), (3,1), (2,2), (2,2)]
print(has_vertical_symmetry(points)) # True
This method works for a set of points and checks for symmetry relative to a vertical axis.