In: Computer Science
Closest and Farthest points. Distance between two points (x1,
y1) and (x2, y2) can be
calculated as d = sqt( (x1 − x2) ^2 + (y1 − y2)^ 2)
. You are given the coordinates of a source
point and three destination points. Write a Python program stored
in a file q8.py that
takes these information as input and determines the closest and
farthest destination
points from the source point.
ex:
Enter source coordinates : 0 0
Enter point A coordinates : 1 4
Enter point B coordinates : -4 5
Enter point C coordinates : -2.4 -0.9
From source point (0.0 , 0.0) ,
Point C ( -2.4 , -0.9) is closest , with distance of 2.56 units
.
Point B ( -4.0 , 5.0) is farthest , with distance of 6.4 units
def readPoint(prompt): points = input(prompt) points = points.split() return float(points[0]), float(points[1]) def distance(p1, p2): return ((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) ** 0.5 points = [] points.append(readPoint('Enter source coordinates : ')) points.append(readPoint('Enter point A coordinates : ')) points.append(readPoint('Enter point B coordinates : ')) points.append(readPoint('Enter point C coordinates : ')) # assume first point to be result maxDis = distance(points[0], points[1]) maxDisPoint = points[1] minDis = distance(points[0], points[1]) minDisPoint = points[1] # check if better points are present for i in range(2, len(points)): d = distance(points[0], points[i]) if d > maxDis: maxDis = d maxDisPoint = points[i] if d < minDis: minDis = d minDisPoint = points[i] print('From source point', points[0]) print('Point', minDisPoint, ' is closest, with distance of', minDis, 'units') print('Point', maxDisPoint, ' is farthest, with distance of', maxDis, 'units')