#-*-encoding:utf-8-*-
"""
向量运算
todoList:
1>向量的数乘、数除需要添加左乘、左除
"""
class vector(object):
def __init__(self, param=[]):
"""
>>> NoneListTest=vector([])
>>> IntTest=vector(1)
>>> FloatTest=vector(-1.1)
>>> StrTest=vector("")
>>> OtherTest=vector((1,2,3))
Traceback (most recent call last):
...
TypeError: Input Param Error
"""
if not param:
self._data = []
#仅接受列表作为参数,如果不是列表切不是单个元素则报错
elif type(param) == type([]):
self._data = param
elif type(param) in [type(1), type(0.1), type('')]:
self._data = [param]
else:
raise TypeError("Input Param Error")
def __len__(self):
"""
返回向量长度
>>> SingleElementTest=vector(1)
>>> len(SingleElementTest)
1
>>> MulElementsTest=vector([1,2,3,4,5])
>>> len(MulElementsTest)
5
"""
return(len(self._data))
def __str__(self):
"""
打印向量
"""
return(str(self._data))
def __add__(self, anotherVector):
"""
计算加法
>>> vector1=vector([1,2,3])
>>> vector2=vector([1,2])
>>> vector1+vector2
Traceback (most recent call last):
...
RuntimeError: The tow vectors have different length
>>> vector2=vector([2,3,4])
>>> print(vector1+vector2)
[3, 5, 7]
>>> vector2=vector([1,2,""])
>>> print(vector1+vector2)
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for +: 'int' and 'str'
"""
if len(self) != len(anotherVector):
raise RuntimeError("The tow vectors have different length")
else:
return(vector([self._data[i] + anotherVector._data[i] for i in range(len(self))]))
def __sub__(self,anotherVector):
"""
计算减法
>>> vector1=vector([1,2,3])
>>> vector2=vector([1,2])
>>> print(vector1-vector2)
Traceback (most recent call last):
...
RuntimeError: The tow vectors have different length
>>> vector2=vector([2,3,4])
>>> print(vector1-vector2)
[-1, -1, -1]
>>> vector2=vector([1,2,""])
>>> print(vector1-vector2)
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for -: 'int' and 'str'
"""
if len(self) != len(anotherVector):
raise RuntimeError("The tow vectors have different length")
else:
return(vector([self._data[i] - anotherVector._data[i] for i in range(len(self))]))
def __mul__(self,number):
"""
计算乘法
>>> vector1=vector([1,2,3])
>>> print(vector1*2)
[2, 4, 6]
>>> print(vector1*1.5)
[1.5, 3.0, 4.5]
"""
return(vector([i*number for i in self._data]))
def __truediv__(self,number):
"""
计算除法
>>> vector1=vector([1,2,3])
>>> print(vector1/2)
[0.5, 1.0, 1.5]
>>> print(vector1/0)
Traceback (most recent call last):
...
ZeroDivisionError: int division or modulo by zero
"""
return(self*(1/number))
if __name__ == '__main__':
import doctest
doctest.testmod()