关于用类表示向量

2024-04-25 14:15:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一些代码方面的帮助! 以下是一些说明:

  • 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.

  • 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

所以,我想知道问题是什么以及如何解决它。 谢谢!!你知道吗


Tags: oftheselflenreturnisdeftype
1条回答
网友
1楼 · 发布于 2024-04-25 14:15:54

此方法提供所需的输出:

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)))

相关问题 更多 >

    热门问题