How to add a distance method - python

I have the following code:
class Point:
"""Two-Dimensional Point(x, y)"""
def __init__(self, x=0, y=0):
# Initialize the Point instance
self.x = x
self.y = y
#property
def magnitude(self):
# """Return the magnitude of vector from (0,0) to self."""
return math.sqrt(self.x ** 2 + self.y ** 2)
def __str__(self):
return 'Point at ({}, {})'.format(self.x, self.y)
def __repr__(self):
return "Point(x={},y={})".format(self.x, self.y)
The class has a function called magnitude. I want to create a function which can tell the magnitude distance between two points. The following is an expected output:
point1 = Point(2, 3)
point2 = Point(5, 7)
print(point1.magnitude)
3.605551275463989
print(point2.magnitude)
8.605551275463989
print(point1.distance(point2))
5.0
I tried doing something like this:
#classmethod
def distance(self):
pointmag1 = point1.magnitude
pointmag2 = point2.magnitude
if pointmag2 > pointmag1:
return pointmag2 - pointmag1
else:
return pointmag1 - pointmag2
This however return an error TypeError: distance() takes 1 positional argument but 2 were given. I also feel like I am taking an incorrect approach to this as nothing other than point1 or point2 would work. Does anyone have anything which could work better? Thanks.
EDIT: I have mmade the follwoing changes:
#classmethod
def distance(self, self2):
pointmag1 = point1.magnitude
pointmag2 = point2.magnitude
if pointmag2 > pointmag1:
return pointmag2 - pointmag1
else:
return pointmag1 - pointmag2
This however returns 4.996773991578637, instead of 5. Any way to change this?
EDIT: I made the following changes:
#classmethod
def distance(self, self2):
pointmag1 = self.magnitude
pointmag2 = self2.magnitude
if pointmag2 > pointmag1:
return pointmag2 - pointmag1
else:
return pointmag1 - pointmag2
This returns the error TypeError: '>' not supported between instances of 'float' and 'property'

You can implement a custom __sub__ method to find the distance:
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
#property
def magnitude(self):
return math.sqrt(self.x ** 2 + self.y ** 2)
def __sub__(self, _point):
return pow(abs(_point.x-self.x)**2 + abs(_point.y-self.y)**2, 0.5)
point1 = Point(2, 3)
point2 = Point(5, 7)
print(point2-point1)
Output:
5.0
Edit: distance implemented as a method:
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def distance(self, _p2):
return pow(abs(self.x-_p2.x)**2 + abs(self.y-_p2.y)**2, 0.5)
point1 = Point(2, 3)
point2 = Point(5, 7)
print(point1.distance(point2))

Related

AttributeError: 'list' object has no attribute 'dist'

I have been working on an assignment for one of my introductory classes. I am almost done with my code and but I keep getting "AttributeError: 'tuple' object has no attribute 'dist'." I understand that the problem starts from midpt function and that I need to return an instance of the class instead of the tuple; however, I have not been able to do that. Could you please take a look at my code? It would be much appreciated.
'''
import math
class Point(object):
# The contructor for Point class
def __init__(self, x = 0, y = 0):
self.x = float(x)
self.y = float(y)
# The getter for x
#property
def x(self):
return self._x
# The setter for x
#x.setter
def x(self, value):
self._x = value
# The getter for y
#property
def y(self):
return self._y
# The setter for y
#y.setter
def y(self, value):
self._y = value
# Function for getting the distance between two points
def dist(self, other):
xVar = (other.x - self.x) ** 2
yVar = (other.y - self.x) ** 2
equation = xVar + yVar
distance = math.sqrt(equation)
return distance
# Function for getting the midpoint
def midpt(self, other):
xVar = (other.x - self.x) / 2
yVar = (other.y - self.y) / 2
midpoint = (xVar,yVar)
return midpoint
# Magic function for printing
def __str__(self):
return "({},{})".format(self.x, self.y)
##########################################################
# ***DO NOT MODIFY OR REMOVE ANYTHING BELOW THIS POINT!***
# Create some points
p1 = Point()
p2 = Point(3, 0)
p3 = Point(3, 4)
# Display them
print("p1:", p1)
print("p2:", p2)
print("p3:", p3)
# Calculate and display some distances
print("distance from p1 to p2:", p1.dist(p2))
print("distance from p2 to p3:", p2.dist(p3))
print("distance from p1 to p3:", p1.dist(p3))
# Calculate and display some midpoints
print("midpt of p1 and p2:", p1.midpt(p2))
print("midpt of p2 and p3:", p2.midpt(p3))
print("midpt of p1 and p3:", p1.midpt(p3))
# Just a few more things...
p4 = p1.midpt(p3)
print("p4:", p4)
print("distance from p4 to p1:", p4.dist(p1))
You might want to change midpoint = (xVar,yVar) to midpoint = Point(xVar, yVar).
In this way, p4 is a Point (and not a tuple!) instance, and you can call the dist method on it.

Python _add_ method

I am trying to override _add_ method. I am getting error :
Point3 = Point1 + Point2
TypeError: unsupported operand type(s) for +: 'Point' and 'Point'
What am I missing? Please help. This was my first Python class.
from math import sqrt
class Point(object):
def __init__(self,x,y,z):
self.x = x
self.y = y
self.z = z
def __str__(self):
return "%i,%i,%i"%(self.x, self.y, self.z)
def _add_(self, other):
TotalX = self.x + other.x
TotalY = self.y + other.y
TotalZ = self.z + other.z
return Point(TotalX, TotalY, TotalZ)
def Distance(self, other):
val =0
val = ((self.x - other.x)**2+ (self.y - other.y)**2 + (self.z - other.z)**2)
return val
print ("Just defined method")
Point1= Point(x=4, y=2, z=9)
Point2= Point(x=5, y=3, z=10)
Point3 = Point1 + Point2
Thanks,
Shruti.
It's __add__, not _add_. All magic methods in Python, such as for addition, use two leading underscores and two trailing underscores. For a detailed reference on the Python data model, including all documented magic methods, please see here.

unable to fix this

I am trying to solve this problem . I am getting error . I can't understand where to fix
class Location(object):
def __init__(self, x, y):
self.x = x
self.y = y
def move(self, deltaX, deltaY):
return Location(self.x + deltaX, self.y + deltaY)
def getX(self):
return self.x
def getY(self):
return self.y
def dist_from(self, other):
xDist = self.x - other.x
yDist = self.y - other.y
return (xDist ** 2 + yDist ** 2) ** 0.5
def __eq__(self, other):
return (self.x == other.x and self.y == other.y)
def __str__(self):
return '<' + str(self.x) + ',' + str(self.y) + '>'
class Campus(object):
def __init__(self, center_loc):
self.center_loc = center_loc
def __str__(self):
return str(self.center_loc)
class MITCampus(Campus):
""" A MITCampus is a Campus that contains tents """
def __init__(self, center_loc, tent_loc=Location(0, 0)):
""" Assumes center_loc and tent_loc are Location objects
Initializes a new Campus centered at location center_loc
with a tent at location tent_loc """
# Your code here
self.center_loc = center_loc
self.tent_loc = tent_loc
def add_tent(self, new_tent_loc):
""" Assumes new_tent_loc is a Location
Adds new_tent_loc to the campus only if the tent is at least 0.5 distance
away from all other tents already there. Campus is unchanged otherwise.
Returns True if it could add the tent, False otherwise. """
# Your code here
try:
self.tent_loc[object] += 1
except:
self.tent_loc[object] = 1
return new_tent_loc in self.tent_loc
def remove_tent(self, tent_loc):
""" Assumes tent_loc is a Location
Removes tent_loc from the campus.
Raises a ValueError if there is not a tent at tent_loc.
Does not return anything """
# Your code here
if tent_loc not in self.tent_loc:
return
self.tent_loc[tent_loc] -= 1
if self.tent_loc[tent_loc] < 1:
del (self.tent_loc[tent_loc])
For example, if c = MITCampus(Location(1,2)) then executing the following sequence of commands:
c.add_tent(Location(2,3)) should return True
c.add_tent(Location(0,0)) should return False
c.add_tent(Location(2,3)) should return False
c.get_tents() should return ['<0,0>', '<1,2>', '<2,3>']
i am getting is error : The class named 'MITCampus' should define a method named get_tents.
def add_tent(self, new_tent_loc):
""" Assumes new_tent_loc is a Location
Adds new_tent_loc to the campus only if the tent is at least 0.5 distance
away from all other tents already there. Campus is unchanged otherwise.
Returns True if it could add the tent, False otherwise. """
# Your code here
try:
self.tent_loc[object] += 1
except:
self.tent_loc[object] = 1
return new_tent_loc in self.tent_loc
This cannot work : object is a builtin that cannot be used as sequence index.
Finding a fast solution is faster than explaining everything ;)
class Location(object):
def __init__(self, x, y):
self.x = x
self.y = y
def move(self, deltaX, deltaY):
return Location(self.x + deltaX, self.y + deltaY)
def getX(self):
return self.x
def getY(self):
return self.y
def dist_from(self, other):
xDist = self.x - other.x
yDist = self.y - other.y
dist = (xDist ** 2 + yDist ** 2) ** 0.5
return dist
def __eq__(self, other):
return (self.x == other.x and self.y == other.y)
def __str__(self):
return '<' + str(self.x) + ',' + str(self.y) + '>'
class Campus(object):
def __init__(self, center_loc):
self.center_loc = center_loc
def __str__(self):
return str(self.center_loc)
class MITCampus(Campus):
""" A MITCampus is a Campus that contains tents """
def __init__(self, center_loc, tent_loc=Location(0, 0)):
""" Assumes center_loc and tent_loc are Location objects
Initializes a new Campus centered at location center_loc
with a tent at location tent_loc """
# Your code here
assert isinstance(center_loc, Location)
assert isinstance(tent_loc, Location)
self.center_loc = center_loc
self.tent_locs = [tent_loc]
def add_tent(self, new_tent_loc):
""" Assumes new_tent_loc is a Location
Adds new_tent_loc to the campus only if the tent is at least 0.5 distance
away from all other tents already there. Campus is unchanged otherwise.
Returns True if it could add the tent, False otherwise. """
# Your code here
assert isinstance(new_tent_loc, Location)
added = False
for tent_loc in self.tent_locs:
if tent_loc.dist_from(new_tent_loc) <= 0.5:
break
else:
self.tent_locs.append(new_tent_loc)
added = True
return added
def remove_tent(self, tent_loc):
""" Assumes tent_loc is a Location
Removes tent_loc from the campus.
Raises a ValueError if there is not a tent at tent_loc.
Does not return anything """
# Your code here
assert isinstance(tent_loc, Location)
position = self.tent_locs.index(tent_loc)
del self.tent_locs[position]
def get_tents(self):
return sorted([str(x) for x in [self.center_loc] + self.tent_locs])
c = MITCampus(Location(1, 2))
assert c.add_tent(Location(2, 3)) # -> True
assert not c.add_tent(Location(0, 0)) # -> Flase
assert not c.add_tent(Location(2, 3)) # -> False
assert c.get_tents() == ['<0,0>', '<1,2>', '<2,3>']
try:
c.remove_tent(Location(6, 6))
print "removal failed"
except ValueError:
# Expected behaviour
pass
c.remove_tent(Location(2, 3))
assert c.get_tents() == ['<0,0>', '<1,2>']
Hope this helped ! Think to my reputation ;)

How do I call on a method from a different class in a different file?

Here is the class (from point.py):
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def adjacent(self, pt1, pt2):
return ((pt1.x == pt2.x and abs(pt1.y - pt2.y) == 1) or
(pt1.y == pt2.y and abs(pt1.x - pt2.x) == 1))
def distance_sq(self, p1, p2):
return (p1.x - p2.x)**2 + (p1.y - p2.y)**2
And say I have this function that is in a different file (actions.py):
import point
def find_nearest(world, pt, type):
oftype = [(e, distance_sq(pt, entities.get_position(e)))
for e in worldmodel.get_entities(world) if isinstance(e, type)]
return nearest_entity(of type)
Notice how this function is calling distance_sq from point.py, when I try running this code, it complains that:
AttributeError: 'module' object has no attribute 'distance_sq'
I can't remember the correct syntax for calling a method from a class in a different file! Any help is appreciated! Thanks.
For your Point class, neither of the methods defined refer to the instance (self) at all. You should make these either functions in the point module, or if you prefer to keep them namespaced in the class, make them static methods:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
#staticmethod
def adjacent(pt1, pt2):
return ((pt1.x == pt2.x and abs(pt1.y - pt2.y) == 1) or
(pt1.y == pt2.y and abs(pt1.x - pt2.x) == 1))
#staticmethod
def distance_sq(p1, p2):
return (p1.x - p2.x)**2 + (p1.y - p2.y)**2
Then import the Point class from point if you use the staticmethod approach:
from point import Point
... Point.distance_sq(pt, entities.get_position(e))
Or import point and use point.distance_sq if you use functions instead.
Possibly a better approach, if both pt and entities.get_position(e) are instances of Point, would be to make pt1 in both methods always be the current instance:
def adjacent(self, point):
return (
(self.x == point.x and abs(self.y - point.y) == 1) or
(self.y == point.y and abs(self.x - point.x) == 1)
)
def distance_sq(self, point):
return (self.x - point.x)**2 + (self.y - point.y)**2
Then you don't need to import point at all, just do:
pt.distance_sq(entities.get_position(e))
You can not call a member method of a class directly without creating an instance of that class first. It looks like your distance_sq method should be outside class declaration like:
In point.py:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def adjacent(self, pt1, pt2):
return ((pt1.x == pt2.x and abs(pt1.y - pt2.y) == 1) or
(pt1.y == pt2.y and abs(pt1.x - pt2.x) == 1))
def distance_sq(p1, p2):
return (p1.x - p2.x)**2 + (p1.y - p2.y)**2
Then you can call this function like:
import point
point.distance_sq(point1, point2)
Or, the good way will be to create a classmethod like:
In point.py:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def adjacent(self, pt1, pt2):
return ((pt1.x == pt2.x and abs(pt1.y - pt2.y) == 1) or
(pt1.y == pt2.y and abs(pt1.x - pt2.x) == 1))
#classmethod
def distance_sq(cls, p1, p2):
return (p1.x - p2.x)**2 + (p1.y - p2.y)**2
Then, call it like:
import point
point.Point.distance_sq(point1, point2)

Add method that works with either a Point Object or a tuple

One of my exercises says to write an add method for Points that works with either a Point object or a tuple:
If the second operand is a Point, the method should return a new Point whose x coordinate is the sum of the x coordinates of the operands, and likewise for the y coordinates.
If the second operand is a tuple, the method should add the first element of the tuple to the x coordinate and the second element to the y coordinate, and return a new Point with the result.
This how far I got and I'm not sure if the tuple portion of my code is accurate. Can someone shed some light how I would call this program for the tuple portion. I think I nailed the first part.
Here is my code:
Class Point():
def__add__(self,other):
if isinstance(other,Point):
return self.add_point(other)
else:
return self.print_point(other)
def add_point(self,other):
totalx = self.x + other.x
totaly = self.y + other.y
total = ('%d, %d') % (totalx, totaly)
return total
def print_point(self):
print ('%d, %d) % (self.x, self.y)
blank = Point()
blank.x = 3
blank.y = 5
blank1 = Point()
blank1.x = 5
blank1.y = 6
That's what I've built so far and I'm not sure how to actually run this with the tuple part. I know if it did blank + blank1 the if portion would run and call the add_point function but how do I initiate the tuple. I'm not sure if I wrote this correctly... please assist.
You can simply derive your class from the tuple (or just implement __getitem__).
class Point(tuple):
def __new__(cls, x, y):
return tuple.__new__(cls, (x, y))
def __add__(self, other):
return Point(self[0] + other[0], self[1] + other[1])
def __repr__(self):
return 'Point({0}, {1})'.format(self[0], self[1])
p = Point(1, 1)
print p + Point(5, 5) # Point(6, 6)
print p + (5, 5) # Point(6, 6)
Alternatively, if you want to be able to use point.x and point.y syntax, you could implement the following:
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
if isinstance(other, Point):
return Point(self.x + other.x, self.y + other.y)
elif isinstance(other, tuple):
return Point(self.x + other[0], self.y + other[1])
else:
raise TypeError("unsupported operand type(s) for +: 'Point' and '{0}'".format(type(other)))
def __repr__(self):
return u'Point ({0}, {1})'.format(self.x, self.y) #Remove the u if you're using Python 3

Categories

Resources