Search code examples
pythonpython-class

calculating distance between two points in python class


I am trying to calculate the distance between 2 points in python using this code :

import math
class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __repr__(self):
        return "Point({0}, {1})".format(self.x, self.y)
    def __sub__(self, other):
        return Point(self.x - other.x, self.y - other.y) #<-- MODIFIED THIS
    
    def distance(self, other):
        p1 = __sub__(Point(self.x , other.x))**2
        p2 = __sub__(Point(self.y,other.y))**2
        p = math.sqrt(p1,p2)
        return p


def dist_result(points):
    points = [Point(*point) for point in points]
    return [points[0].distance(point) for point in points]

but it is returning:

NameError: name '__sub__' is not defined

can you please show me how to correctly write that function ?

so I am expecting an input of:

𝑃1=(𝑥1,𝑦1)  and  𝑃2=(𝑥2,𝑦2) 

and I would like to calculate the distance using:

𝐷=|𝑃2−𝑃1|=(𝑥1−𝑥2)^2+(𝑦1−𝑦2)^2

Solution

  • The only formula you need is the Pythagorean theorem, and you don't need to create some temporary point, just do:

    def distance(self, other):
        dx = (self.x - other.x) ** 2
        dy = (self.y - other.y) ** 2
        return math.sqrt(dx + dy)
    

    The __sub__ is to override the minus - operator, between Point instances