unable to fix this - python

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 ;)

Related

How to add a distance method

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))

Python: 2 classes importing each other causes an error?

So I have the following directory setup:
Project
Misc Packages and Modules
resources
shapes
Rectangle.py
Rectangle2D.py
Rectangle is just a conceptual rectangle that isn't ever drawn (using Tkinter) but is there for collision and bounds. Rectangle2D is used as a subclass to draw or fill a Rectangle. The classes before I got the error were as followed:
Rectangle.py
class Rectangle(object):
_x = -1
_y = -1
_w = -1
_h = -1
def __init__(self, x, y, w, h):
self._x = x
self._y= y
self._w = w
self._h = h
def intersects(self, other):
if isinstance(other, Rectangle):
if (self._x + self._w) > other._x > self._x and (self._y + self._h) > other._y > self._y:
return True
elif (self._x + self._w) > (other._x + other._w) > self._x and (self._y + self._h) > other._y > self._y:
return True
elif (self._x + self._w) > other._x > self._x and (other._y + other._h) > self._y > other._y:
return True
elif (self._x + self._w) > (other._x + other._w) > self._x and (other._y + other._h) > self._y > other._y:
return True
else:
return False
else:
return False
def __eq__(self, other):
return self._x == other._x and self._y == other._y and self._w == other._w and self._h == other._h
Rectangle2D.py
from tkinter import Canvas
from .Rectangle import Rectangle
class Rectangle2D(Rectangle):
def __init__(self, x, y, w, h):
super(Rectangle2D, self).__init__(x, y, w, h)
self.color = 'black'
self.id = None
def draw_rect(self, canvas):
if isinstance(canvas, Canvas):
self.id = canvas.create_rectangle(self._x, self._y, self._x + self._w, self._y + self._h, outline=self.color)
return True
else:
print("Improper Parameter Type")
return False
def fill_rect(self, canvas):
if isinstance(canvas, Canvas):
self.id = canvas.create_rectangle(self._x, self._y, self._x + self._w, self._y + self._h, fill=self.color)
return True
else:
print("Improper Parameter Type")
return False
Everything was working fine until I wanted to add a method to Rectangle.py that would return a Rectangle2D.py. This record the following line to be added to Rectangle.py in addition to the method:
from .Rectangle2D import Rectangle2D
This resulted in the following error:
from .Rectangle import Rectangle
ImportError: cannot import name 'Rectangle'
What is causing this error and how do I fix it?
Also note I am running Python 3.6

Create a picklable Python class

I am trying to create some custom Python classes for my application. When I try to debug my code I can not pick the instances of my custom classes, I receive the error "Object XXX is not picklable".
I found this page https://docs.python.org/3/library/pickle.html#what-can-be-pickled-and-unpickled but I don't understand how I should implement the methods that make my class picklable.
For example how would you modify the following classes so that I can pick instances of them?
class Point3D:
def __init__ (self, x, y, z):
self.x = x
self.y = y
self.z = z
def move(self, vector):
self.x += vector.x
self.y += vector.y
self.z += vector.z
return
def isValidPoint(self):
isNotValid = False
isNotValid = math.isnan(self.x) or math.isnan(self.y) or math.isnan(self.z)
return not isNotValid
And
class PointCloud3D:
def __init__ (self):
self.points = []
def getNumberOfPoints(self):
return len(self.points)
def addPoint(self, point):
self.points.append(point)
return
def addPointCloud3D(self, additionalPointCloud3D):
for self.point in additionalPointCloud3D:
self.addPoint(point)
def getCloudCenter(self):
numberOfPoints = self.getNumberOfPoints()
centersSumX = 0
centersSumY = 0
centersSumZ = 0
for point in self.points:
centersSumX = centersSumX + point.x
centersSumY = centersSumY + point.y
centersSumZ = centersSumZ + point.z
centerX = centersSumX/numberOfPoints
centerY = centersSumY/numberOfPoints
centerZ = centersSumZ/numberOfPoints
center = Point3D(float(centerX), float(centerY) , float(centerZ))
return center
While here you can find the code that I am trying to debug:
from classDatabase import Point3D, PointCloud3D
testPoint1 = Point3D(1.5, 0.2, 2.3)
testPoint2 = Point3D(3.5, 1.2, 5.3)
testPointCloud3D = PointCloud3D()
testPointCloud3D.addPoint(testPoint1)
testPointCloud3D.addPoint(testPoint2)
Finally a screenshot of the issue:

Overriding the plus operator for a user defined vector class in Python

I have written a class to work with three dimensional vectors as follows
class vector(object):
def __init__(self, x=None, y=None, z=None, angle=None):
if angle == None:
self.x, self.y, self.z = x, y, z
if angle != None:
if angle == "rad":
self.r, self.theta, self.phi = x, y, z
if angle == "deg":
self.r = x
self.theta = y * 2 * pi / 360.
self.phi = z * 2 * pi / 360.
self.x = self.r * sin(self.theta) * cos(self.phi)
self.y = self.r * sin(self.theta) * sin(self.phi)
self.z = self.r * cos(self.theta)
def write(self):
file.write("[" + str(self.x) + ",\t" + str(self.y) + ",\t" + str(self.z) + "]")
def write_sph(self):
file.write("[" + str(self.mag()) + ",\t" + str(self.gettheta()) + ",\t" + str(self.getphi()) + "]")
def getx(self):
return self.x
def gety(self):
return self.y
def getz(self):
return self.z
def setx(self, x):
self.x = x
def sety(self, y):
self.y = y
def setz(self, z):
self.z = z
def square(self):
return self.x*self.x + self.y*self.y + self.z*self.z
def mag(self):
return sqrt(self.square())
def gettheta(self):
return arccos(self.z / self.mag())
def getphi(self):
return arctan2(self.y, self.x) # sign depends on which quadrant the coordinates are in
def __add__(self, vector(other)):
v_sum = vector(other.gettx() + self.gettx(), other.getty() + self.getty(), other.getty() + self.getty())
return v_sum
In the last definition I am attempting to override the operator for addition. The definition works by calling a new vector named other and adding its x,y,z components to the corresponding components of self. When I run the code I'm told the syntax for the definition is invalid. How do I correctly define the vector argument for this overriding definition? Also what difference would changing the definition from def __ add __ to simply def add make? i.e what do the underscores denote?
You shouldn't have vector(other) in your parameter list - just say other. Also, you'll need to fix the typos in the add method:
def __add__(self, other):
v_sum = vector(other.getx() + self.getx(), other.gety() + self.gety(), other.getz() + self.getz())
return v_sum

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