The questions asks to "Write a method add_point that adds the position of the Point object given as an argument to the position of self". So far my code is this:
import math
epsilon = 1e-5
class Point(object):
"""A 2D point in the cartesian plane"""
def __init__(self, x, y):
"""
Construct a point object given the x and y coordinates
Parameters:
x (float): x coordinate in the 2D cartesian plane
y (float): y coordinate in the 2D cartesian plane
"""
self._x = x
self._y = y
def __repr__(self):
return 'Point({}, {})'.format(self._x, self._y)
def dist_to_point(self, other):
changex = self._x - other._x
changey = self._y - other._y
return math.sqrt(changex**2 + changey**2)
def is_near(self, other):
changex = self._x - other._x
changey = self._y - other._y
distance = math.sqrt(changex**2 + changey**2)
if distance < epsilon:
return True
def add_point(self, other):
new_x = self._x + other._x
new_y = self._y + other._y
new_point = new_x, new_y
return new_point
However, I got this error message:
Input: pt1 = Point(1, 2)
--------- Test 10 ---------
Expected Output: pt2 = Point(3, 4)
Test Result: 'Point(1, 2)' != 'Point(4, 6)'
- Point(1, 2)
? ^ ^
+ Point(4, 6)
? ^ ^
So I'm wondering what is the problem with my code?
Your solution returns a new tuple without modifying the attributes of the current object at all.
Instead, you need to actually change the object's attributes as per the instructions and don't need to return anything (ie, this is an "in-place" operation).
def add_point(self, other):
self._x += other._x
self._y += other._y
Related
I'm trying to solve the tasks (text below), but I have a problem with the second point, i.e. method in it that displays the length of the segment and the positions of the start and end points.-
I don't really know how to write it, Could someone look at the code and give some hints?
Define a Point class with x, y fields and a method displaying the
point's position (eg "point (2,3)").
Then create a class Segment that will inherit from the class point.
Create a method in it that displays the length of the segment and the
positions of the start and end points.
Then define the Triangle class which will contain 3 Points,
automatically determined 3 Sections (walls) of them and included a
method for displaying the surface area of the perimeter.
code:
from math import sqrt, hypot
class Point:
def __init__(self, x_init, y_init):
self.x = x_init
self.y = y_init
def __str__(self):
return "Point(%s,%s)"%(self.x, self.y)
class Segment(Point):
def distance(self): **!-probably a badly written method**
return ((self.x ** 2) + (self.y ** 2)) ** 0.5
def position(self, p): **!-probably a badly written method**
dx = self.x - p.X
dy = self.y - p.Y
return hypot(dx, dy)
class Triangle(Point):
def __init__(self, x, y, z):
Point.__init__(self, x, y)
self.z = z
def __str__(self):
return "Point(x %s ,y %s, z %s )" % (self.x, self.y, self.z)
def __area__(a, b, c):
s = (a + b + c) / 2
return (s * (s - a) * (s - b) * (s - c)) ** 0.5
def __perimeter__(a, b, c):
s = (a + b + c)
return s
Task 2 is just wrong. Segment needs to contain 2 points, so it can't inherit from Point. It should be:
class Segment:
def __init__(self, start, end):
self.start = start
self.end = end
def distance(self):
dist = ((self.start.x - self.end.x) ** 2 + (self.start.y - self.end.y) ** 2) ** 0.5
print(f"distance from {self.start} to {self.end} is {dist}"
import math
class Vector:
def __init__(self,x,y):
self.x= x
self.y =y
def add(self,other):
new_x = self.x + other.x
new_y = self.y + other.y
return Vector(new_x,new_y)
def subtract(self,other):
new_x = self.x - other.x
new_y = self.y - other.y
return Vector(new_x,new_y)
def scale(self,factor):
new_x = self.x * factor
new_y = self.y * factor
return Vector(new_x,new_y)
def length(self,other):
r_squared = self.x ** 2 + self.y **2
return Vector(r_squared)
I've been trying to test this code that I was given, how am I able to test this using some numbers so that I am able to learn to understand what each function in this code actually does. I am able to see what it does from looking at the code but I also want to reassure that what I am predicting it to do is actually what it does.
Thank you in advance!
Add a checker for your code at the very end of yor file:
if __name__=="__main__":
vec1 = Vector(0, 0)
vec2 = Vector(2,2)
vec3 = vec1.add(vec2)
print(vec1, vec2, vec3)
#add other tests
You could add an override to a built in function in the Vector class for printing instances in a human readable way.
def __repr__(self):
return 'Vector: ({}, {})'.format(self.x, self.y)
Then you might want to fix the length function. It should only return a number and not another Vector. Additionally, it should return the square root of the sum. For example the vector (3, 4) should have a length of 5, not 25. Also, the length method does not need vector supplied as a param.
Once these are fixed up you can add this to the bottom of the file and run the script in the terminal like so: python vec.py
if __name__ == '__main__':
v1 = Vector(0,0)
v2 = Vector(3,4)
print('v1', v1)
print('v2', v2)
print('v1 + v2', v1.add(v2))
print('v2.length', v2.length())
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(point1.distance(point2))
5.0
I tried doing something like this:
#classmethod
def distance(self, self1, self2):
pointmag1 = self1.magnitude
pointmag2 = self2.magnitude
bsmag = pointmag1 - pointmag2
bsmag2 = pointmag2 - pointmag1
if pointmag2 > pointmag1:
return combsmag2
else:
return combmag
This code always gives me the TypeError: distance() missing 1 required positional argument: 'self2'. Any way to fix this?
You have a few options. If you'd like to explicitly pass both Point instances to your distance function, define it outside the Point class:
def distance(point1, point2):
pointmag1 = point1.magnitude
pointmag2 = point2.magnitude
...
and call it with:
point1 = Point(2, 3)
point2 = Point(5, 7)
distance(point1, point2)
If you'd like to keep the interface you wrote in your example though - point1.distance(point2) - then you need distance to be an instance method, not a class method:
class Point:
# all your other code still here
def distance(self, other):
pointmag1 = self.magnitude
pointmag2 = other.magnitude
...
In this case self is point1, and now other is point2.
(Note your distance method won't work as is, the variables combsmag and combsmag2 are never defined, but that's unrelated to the error you're asking about.)
from math import pi
class Circle(object):
'Circle(x,y,r)'
def __init__(self, x=0, y=0, r=1):
self._r = r
self._x = x
self._y = y
def __repr__(self):
return 'Circle({},{},{})'.\
format(self.getx(), self.gety(),\
self.getr())
#silly, but has a point: str can be different from repr
def __str__(self):
return 'hello world'
def __contains__(self, item):
'point in circle'
px, py = item
return (self.getx() - px)**2 + \
(self.gety() - py)**2 < self.getr()**2
def getr(self):
'radius'
return self._r
def getx(self):
'x'
self._lst.append(self._x)
return self._x
def gety(self):
'y'
self._lst.append(self._y)
return self._y
def setr(self,r):
'set r'
self._r = r
def setx(self,x):
'set x'
self._x = x
def sety(self,y):
'set y'
self._y = y
def move(self,x,y):
self._x += x
self._y += y
def concentric(self, d):
d = self._list
def area(self):
'area of circle'
return (self.getr())**2*pi
def circumference(self):
'circumference of circle'
return 2*self.getr()*pi
My question is worded kinda awkwardly but what I am trying to do is check if 2 different circles have the same center (x,y). I think the easiest way to solve this would be to input the 2 points into a list but I am not sure how to compare the 2 lists as every time i try my code it adds everything to the same list
Add the following method to your Circle class.
def equal_center(self, other):
'check if another circle has same center'
return (self._x == other._x) & (self._y == other._y)
Usage
C1 = Circle(3, 5, 8)
C2 = Circle(3, 5, 10)
C3 = Circle(3, 2, 1)
C1.equal_center(C2) # True
C1.equal_center(C3) # False
I would recommend creating a function which takes two circle objects and returns if the coordinates are the same or not by comparing the x and y values of each object:
def same_center(circle_1, circle_2):
if circle_1.getx() == circle_2.getx() and circle_1.gety() == circle_2.gety():
return True
else:
return False
This solution is much easier than using lists and should be easy to implement.
If you have two instances of the class...
a = Circle(0,0,1)
b = Circle(0,0,1)
You could add them to a list of circles...
circles = [a,b]
And loop through the list, checking their values...
for i in circles:
for j in filter(lambda x : x != i, circles):
if i._x == j._x and i._y == j._y:
return True #two circles have same center
This should work for n instances of the class, though if its only two you want to check
if a._x == b._x and a._y == a._y:
return True
G'day! When I know the slope and y-intercept of a line, I need to calculate an x-value that is 1 unit out from the line.
For example, if pointA = (4,5), and I set a line going from it with 0 slope (and therefore 5 as the y-intercept), then the x value I want would be 5. If the slope were undefined (vertical), then the x value would be 4. And so on.
So far, I calculate x as x = m(point[0]+1)-b. This doesn't work so well for vertical lines, however.
This and this are similar, but I can't read C# for the first, and on the second one, I don't need to eliminate any possible points (yet).
This is kind of hitting a nail with a sledge hammer, but if you're going to be running into geometry problems often, I'd either write or find a Point/Vector class like
import math
class Vector():
def __init__(self, x=0.0, y=0.0, z=0.0):
self.x = x
self.y = y
self.z = z
def __add__(self, other):
self.x += other.x
self.y += other.y
self.z += other.z
return self
def __sub__(self, other):
self.x -= other.x
self.y -= other.y
self.z -= other.z
return self
def dot(self, other):
return self.x*other.x + self.y*other.y + self.z*other.z
def cross(self, other):
tempX = self.y*other.z - self.z*other.y
tempY = self.z*other.x - solf.x*other.z
tempZ = self.x*other.y - self.y*other.x
return Vector(tempX, tempY, tempZ)
def dist(self, other):
return math.sqrt((self.x-other.x)**2 + (self.y-other.y)**2 + (self.z-other.z)**2)
def unitVector(self):
mag = self.dist(Vector())
if mag != 0.0:
return Vector(self.x * 1.0/mag, self.y * 1.0/mag, self.z * 1.0/mag)
else:
return Vector()
def __repr__(self):
return str([self.x, self.y, self.z])
Then you can do all kinds of stuff like find the vector by subtracting two points
>>> a = Vector(4,5,0)
>>> b = Vector(5,6,0)
>>> b - a
[1, 1, 0]
Or adding an arbitrary unit vector to a point to find a new point (which is the answer to your original question)
>>> a = Vector(4,5,0)
>>> direction = Vector(10, 1, 0).unitVector()
>>> a + direction
[4.995037190209989, 5.099503719020999, 0.0]
You can add more utilities, like allowing Vector/Scalar operations for scaling, etc.