'How to fix the assertion error in this problem?
I'm having a problem fixing the error below. I'm returning correct outputs, then the assertion error occurred. How to fix it? What should I do?
Example Usage:
from vector import Vector
v1 = Vector(1, 1, 0) # Initialize vector <1,1,0>
v2 = Vector(2, 1, 3) # Initialize vector <2,1,3>
print(v1) # Should print "<1,1,0>"
print(v2) # Should print "<2,1,3>"
v3 = v1 + v2
print (v3) # v3 is <3,2,3>
v4 = v1 * 3
print (v4) # v4 is <3,3,0>
v5 = v2 * 2
print(v5) # v5 is <4,2,6>
c_p = v1.cross_product(v2)
print(c_p) # returns <3,-3,-1>
d_p = v1.dot_product(v2)
print(d_p) # returns 3
m = v1.magnitude() # returns 1.4142135623730951
print (m)
This is my code:
import math
class Vector:
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
def __str__(self):
return '<{}, {}, {}>'.format(self.x,self.y,self.z)
def __add__(self, other):
return Vector(self.x+other.x,self.y+other.y,self.z+other.z)
def __mul__(self, other=int()):
return Vector(self.x*other,self.y*other,self.z*other)
def cross_product(self, other):
c = (self.y*other.z - self.z*other.y,self.z*other.x- self.x*other.z,self.x*other.y - self.y*other.x)
return c
def dot_product(self, other):
d = (self.x*other.x + self.y*other.y + self.z*other.z)
return d
def magnitude (self):
e = (math.sqrt(self.x**2 + self.y**2 + self.z**2))
return e
Outputs from my code:
<1, 1, 0>
<2, 1, 3>
<3, 2, 3>
<3, 3, 0>
<4, 2, 6>
(3, -3, -1)
3
1.4142135623730951
The error, I am guessing that this could be due to whitespaces? I tried resolving it though.
, line 12, in test_vector
self.assertEquals(str(v1), "<2,1,-2>")
AssertionError: '<2, 1, -2>' != '<2,1,-2>'
- <2, 1, -2>
? - -
+ <2,1,-2>
Solution 1:[1]
Just like this:
class Vector:
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
def __str__(self):
return '<{},{},{}>'.format(self.x,self.y,self.z)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | HuLu ViCa |
