Akule8
Akule8

Reputation: 37

Quadratic Distance

I have a problem with a task. I need to write an python code which calculates a quadratic distance between two points.

The formula is: D^2 = (x1 - x2)^2 + (y1 - y2)^2

and my code:

def quadratic_distance(p1: Point, p2: Point) -> float:
# YOUR CODE HERE
class p1:
    def __init__(self, x1, y1):
        self.x = x1
        self.y = y1
class p2:
    def __init__(self, x2, y2):
        self.x = x2
        self.y = y2
result1 = p1.x - p2.x 
result2 = result1**2
result3 = p1.y - p2.y
result4 = result3**2
result5 = result2 + result4
return result5

but my problem is that i get an attribute error

AttributeError: type object 'p1' has no attribute 'x'

I am fairly new in the object oriented programming and have been stuck at this task. I hope someone can help me

assert quadratic_distance(Point(0, 0),Point(1, 1)) == 1.75

should be the solution

Upvotes: 0

Views: 904

Answers (3)

ARUN KUMAR NAYAK
ARUN KUMAR NAYAK

Reputation: 1

Although you have declared the class p1 and p2 but you haven't created any object. So, you are getting this error. x and y are the instances of class p1 and p2 you can't access by their class name. Either define x and y as class variables inside the class or define a object each of class p1 and p2 like given below. p1ob=p1(4,5) p2ob=p2(5,6)

Upvotes: 0

Yashi
Yashi

Reputation: 1

You are getting an error because you have not created an object of the class. In python, x is not an attribute of a class but x is the attribute of its object.

So you can do it as:

class p1:
    def __init__(self, x1, y1):
        self.x = x1
        self.y = y1
class p2:
    def __init__(self, x2, y2):
        self.x = x2
        self.y = y2

p1_obj = p1(5,5)  
p2_obj = p2(10,10)   
result1 = p1_obj.x - p2_obj.x 
result2 = result1**2
result3 = p1_obj.y - p2_obj.y
result4 = result3**2
result5 = result2 + result4
return results

You can further improve it as p1 and p2 have the same properties (data member and member function) so we can just use one class named p (or any other name) and create two object p1 and p2 of the class

Upvotes: 0

Hirusha Fernando
Hirusha Fernando

Reputation: 1265

According to your formula, quadratic distance between Point(0,0) and Point(1,1) is 2. Not 1.75

This is my code. Try this

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y


P1 = Point(0,0)
P2 = Point(1,1)

def quadratic_distance(p1: Point, p2: Point) -> float:
    result1 = p1.x - p2.x 
    result2 = result1**2
    result3 = p1.y - p2.y
    result4 = result3**2
    result5 = result2 + result4
    return result5

print(quadratic_distance(P1, P2))

Upvotes: 3

Related Questions