Home > Enterprise >  Use python class to calculate euclidean distance between two points
Use python class to calculate euclidean distance between two points

Time:10-31

i am doing a question in class python. in the test results, there is a difference between my results with the answer,

in the last test,

The nearest point to Point(-30, 9) is Point(-19, 19), but my code prints Point(-20,20)

i do not know where's wrong? please help me. thanks this is the question here is my codes

here is my code.

import math

class Point:
    """Defines the Point class for a 2D point.
    Data attributes: 
                    x - the x-coordinate of type float
                    y - the y-coordinate of type float
    """    
    
    def __init__(self, x, y):
        """Creates a new Point object"""
        self.x = x
        self.y = y
        
    def __repr__(self):
        """A string representation of this Point"""
        return f"Point({self.x}, {self.y})"
        
def euclidean_distance(point1, point2):
    """returns the euclidean distance between two points"""
    return math.sqrt((point1.x-point2.x) ** 2   (point1.y-point2.y) **2)

def closest_point(centre, points):
    """returns the nearest point in the list to the centre."""
    new_dict = {}
    for point in points:
        distance = math.sqrt((centre.x-point.x) ** 2   (centre.y-point.y) **2)
        new_dict[distance] = point
    for keys,values in new_dict.items():
        min_key = min(new_dict.keys())
        return new_dict[min_key]

and the tests results below:

the tests

please help me with this, where's wrong in my code and how to modify it to get the expected results. thanks

CodePudding user response:

Issue is in routine closest_point

  • Using the dictionary you're setting last point pair which has that distance (the issue is multiple pairs have the same distance)
  • in below code the first pair which has the distance is used (answer agrees with the linked solution)
  • incorrect looping over new_dict to find closest point (dict not needed)

Code

def closest_point(centre, points):
    """returns the nearest point in the list to the centre."""
    min_dist = float('inf')    # initialize to infinity
    min_point = None
    for point in points:
        distance = euclidean_distance(centre, point) # use function rather than recoding
        if distance < min_dist:
            min_dist = distance  # using the first point with this min distance
            min_point = point
    return min_point
  • Related