1. 程式人生 > >python中 使用列表推導自定義向量的加減乘

python中 使用列表推導自定義向量的加減乘

# coding=utf-8
class Vector(object):
    """docstring for Vector"""
    """根據座標軸列表輸入 建立向量, 並建立該向量所處的空間維度"""
    def __init__(self, coordinates):
        super(Vector, self).__init__()
        try:
            if not coordinates:
                raise ValueError
            self.coordinates = tuple(coordinates)
            self.dimension = len(coordinates)    
        except ValueError:
            raise ValueError('The coordinates must be nonempty')
        except TypeError:
            raise TypeError('The coordinates must be an iterable')

    # '''能夠使python的內建print函式 輸出向量座標軸'''

    def __str__(self):
        return 'Vector: {}'.format(self.coordinates)

    def __eq__(self, v):
         return self.coordinates == v.coordinates

    def plus(self,v):
        # 使用列表推導
       new_corrdinate =[x+y for x,y in  zip(self.coordinates, v.coordinates)]
       # 使用for迴圈
       # new_corrdinate = []
       # n = len(self.coordinates)
       # for i in range(n):
       #       new_corrdinate.append(self.coordinates[i] + v.coordinates[i])
       return Vector(new_corrdinate)

    def minus(self,v):
        new_corrdinate = [x-y for x,y in zip(self.coordinates, v.coordinates)]
        return Vector(new_corrdinate)

    def scalarMultiply(self,num):
        new_corrdinate =[num * x for x in self.coordinates]
        return Vector(new_corrdinate)

myVector = Vector([1,2,3])
otherVector = Vector([2,3,3])

print myVector.plus(otherVector)
print myVector.minus(otherVector)
print myVector.scalarMultiply(3)


# 輸出結果
# Vector: (3, 5, 6)
# Vector: (-1, -1, 0)
# Vector: (3, 6, 9)
# [Finished in 0.1s]