Seif Mahdi
Seif Mahdi

Reputation: 53

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

Upvotes: 0

Views: 1384

Answers (2)

azro
azro

Reputation: 54148

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

Upvotes: 1

Samwise
Samwise

Reputation: 71444

__sub__ is an instance method, not a global function. The general way you call an instance method is as an attribute on the instance, e.g.:

difference = p1.__sub__(p2)

which is equivalent to:

difference = Point.__sub__(p1, p2)

Since __sub__ is a magic method, you can also invoke it via the subtraction operator:

difference = p1 - p2

To implement your distance method in terms of your __sub__ method I think you want something along the lines of:

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

Upvotes: 1

Related Questions