我需要一些代码方面的帮助! 以下是一些说明:
v.mul(other) : If other is of type Vector , returns the dot > product of v and other , which is the sum of the products of the > corresponding components; raises an assertion error if other is of > different dimension. If other is of type int or float , returns a new vector resulting from the scalar multiplication of v with other . If > the type of other is not Vector , int , or float , raises an assertion > error.
=======================================================================================
代码如下:
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
所以,我想知道问题是什么以及如何解决它。 谢谢!!你知道吗
此方法提供所需的输出:
相关问题 更多 >
编程相关推荐