[PYTHON]Help adding two 3d vectors in a class? My code is included. Can you alte
ID: 3598283 • Letter: #
Question
[PYTHON]Help adding two 3d vectors in a class?
My code is included. Can you alter the function add, and make it so it can add two vectors together and return a new vector sum of the two? Thanks
code:
from math import *
class Vector:
x = 0
y = 0
z = 0
def __init__(self,x,y,z):
self.x = float(0)
self.y = float(0)
self.z = float(0)
def __str__(self):
s = str('vec3d: ' + str(self.x) + ', '+ str(self.y) + ', '+ str(self.z))
return s
def get_xyz(self):
return x,y,z
def set_xyz(self,a,b,c):
self.x = float(a)
self.y = float(b)
self.z = float(c)
def __add__(self, other)
hacer = Vector(0,0,0)
print(hacer)
hacer.set_xyz(3.2,4.4,8.5)
print(hacer)
r = hacer.magnitude()
print(r)
link(https://gist.github.com/anonymous/610b67f6f6942c2d571f35600b0ba61f)
Test 3 add A vec3d: 1.50, 2.00, 3.00 B vec3d: 5.30, 8.00, 11.00 C vec3d: 6.80, 10.00, 14.00 actual C vec3d: 6.80, 10.00, 14.00 expectExplanation / Answer
I have modified the add method as asked.
Here is the code
---------------------------------------------------------------------------------------------------
from math import *
class Vector:
x = 0
y = 0
z = 0
def __init__(self,x,y,z):
self.x = float(x)
self.y = float(y)
self.z = float(z)
def __str__(self):
s = str('vec3d: ' + str(self.x) + ', '+ str(self.y) + ', '+ str(self.z))
return s
def get_xyz(self):
return self.x,self.y,self.z
def set_xyz(self,a,b,c):
self.x = float(a)
self.y = float(b)
self.z = float(c)
def __add__(self, other):
x1,y1,z1 = other.get_xyz()
x2 = self.x + x1
y2 = self.y + y1
z2 = self.z + z1
return x2,y2,z2
hacer1 = Vector(3.2,4.4,8.5)
print hacer1
hacer2 = Vector(2.3,3.4,7.8)
print hacer2
r1,r2,r3 = hacer1.__add__(hacer2)
result = Vector( r1,r2,r3 )
print result
-----------------------------------------------------------------------------------------------------------------
/* hope this helps */
/* if any queries please comment */
/* thank you */
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.