Answer to Question #334329 in Python for reyadh

Question #334329

You will be given a list of tuples where each tuple indicates a point i.e. (x, y) in a 2-dimensional coordinate system. You need to write a python program to find the minimum distance and the point that is closest to the origin i.e. (0,0)

Hint:

The formula of distance =√ [ (x₂ - x₁)² + (y₂ - y₁)²]

As you are calculating the distance from the origin (0,0), you can simply use distance = √ [ (x²+y²)] 

You can create a list of distances from each point and sort that list using your personal favorite sorting algorithm.


Sample Input 1 

points = [(5,3), (2,9), (-2,7), (-3,-4), (0,6), (7,2)] 

Sample Output 1 

Minimum distance = 5.0 

Here the closest point is (-3,-4) which has a distance of 5.0 from the origin.


Sample Input 2 

points = [(1,7), (4,5), (-1,7), (-2,0), (1,1), (5,-1)] 

Sample Output 2 

Minimum distance = 1.4142135623730951 Here the closest point is (1,1) which has a distance of 1.4142135623730951 from the origin.


1
Expert's answer
2022-04-27T18:25:14-0400
import math


def dist(Px, Py):
    return math.sqrt(Px**2 + Py**2)


P = [(5, 3), (2, 9), (-2, 7), (-3, -4), (0, 6), (7, 2)]
n = len(P)
distance = []
for i in range(n):
    distance.append(dist(P[i][0], P[i][1]))
min_dist = min(distance)
min_index = distance.index(min_dist)


print("Minimum distance = ", min_dist)
print("Here the closest point is " + str(P[min_index]) +
      " which has a distance of " + str(min_dist) + " from the origin.")

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS