Kata: Vector class

解法1:


In [1]:
import numpy as np

class Vector:
    def __init__(self, vlst):
        self.v = np.array(vlst)
    def toString(self):
        return tuple(self.v).__str__().replace(' ','')
    def add(self, vector):
        try:
            return Vector(self.v + vector.v)
        except:
            print('Error: two vectors with different lengths!')
    def subtract(self, vector):
        try:
            return Vector(self.v - vector.v)
        except:
            print('Error: two vectors with different lengths!')
    def dot(self, vector):
        try:
            return np.dot(self.v, vector.v)
        except:
            print('Error: two vectors with different lengths!')
    def norm(self):
        return np.linalg.norm(self.v)
    def equals(self, vector):
        return np.array_equal(self.v, vector.v)
    
    
a = Vector([1,2,3])
b = Vector([3,4,5])
c = Vector([5,6,7,8])
print(a.add(b).v) # should return Vector([4,6,8])
print(a.subtract(b).v) # should return Vector([-2,-2,-2])
print(a.dot(b)) # should return 1*3+2*4+3*5 = 26
print(a.norm()) # should return sqrt(1^2+2^2+3^2)=sqrt(14)
a.add(c) # raises an exception


[4 6 8]
[-2 -2 -2]
26
3.74165738677
Error: two vectors with different lengths!

In [2]:
a.toString() == '(1,2,3)'


Out[2]:
True