Python 关于使用类的向量
我需要一些代码帮助! 以下是一些说明:Python 关于使用类的向量,python,class,python-3.x,Python,Class,Python 3.x,我需要一些代码帮助! 以下是一些说明: v、 mul(other):如果other是Vector类型,则返回v和other的点>积,即> 相应的组件;如果其他组件的属性> 不同的维度。如果另一个是int或float类型,则返回一个新的 v与其他变量的标量乘法得到的向量。如果>的类型不是Vector、int或float,则会引发 断言>错误 v、 rmul(其他):定义与v.mul(其他)完全相同 ==============================================
- v、 mul(other):如果other是Vector类型,则返回v和other的点>积,即> 相应的组件;如果其他组件的属性> 不同的维度。如果另一个是int或float类型,则返回一个新的 v与其他变量的标量乘法得到的向量。如果>的类型不是Vector、int或float,则会引发 断言>错误
- v、 rmul(其他):定义与v.mul(其他)完全相同
class Vector(object):
vec = []
def __init__(self, l):
self.vec = l
def dim():
return len(self.vec)
def __getitem__(self, i):
return self.vec[i - 1]
def __setitem__(self, i, x):
self.vec[i - 1] = x
def __str__(self):
s = 'Vector: ['
for i in range(0, len(self.vec)):
s = s + str(self.vec[i])
if i < len(self.vec) - 1:
s = s + ', '
s = s + ']'
return s
def __add__(self, other):
assert(type(other) == Vector)
v = self.vec
for i in range(0, len(v)):
v[i]=v[i] + other[i+1]
x = Vector(v)
return x
def __mul__(self, other):
if type(other) == type(self):
v = self.vec
for i in range(0, len(v)):
v[i]=v[i]*other[i+1]
x = Vector(v)
return sum(x)
elif type(other) == type(1) or type(other) == type(1.0):
v = self.vec
for i in range(0, len(v)):
v[i] = v[i] *other
x = Vector(v)
return x
def __rmul__(self, other):
return self.__mul__(other)
>>> v1 = Vector([2, 3, 4]); v2 = Vector([1, 2, 3])
>>> print(v2 * 2); print(2 * v2)
Vector: [2, 4, 6]
Vector: [4, 8, 12]
>>> print(v1 * v2); print(v2 * v1)
128
1376
但是,正确的输出是:
>>> v1 = Vector([2, 3, 4]); v2 = Vector([1, 2, 3])
>>> print(v2 * 2); print(2 * v2)
Vector: [2, 4, 6]
Vector: [2, 4, 6]
>>> print(v1 * v2); print(v2 * v1)
20
20
所以,我想知道问题是什么以及如何解决它。
谢谢 此方法提供所需的输出:
def __mul__(self, other):
if isinstance(other, self.__class__):
if len(self.vec) != len(other.vec):
raise AssertionError('Vectors have different lengths '
'of {} and {}'.format(len(self.vec), len(other.vec)))
return sum(x * y for x, y in zip(self.vec, other.vec))
elif isinstance(other, (int, float)):
return Vector([x * other for x in self.vec])
else:
raise AssertionError('Cannot use type ' + str(type(other)))
谢谢但是,当我添加return“Vector:+[x*other for x in self.vec]时,它是错误的,你能帮我吗?请