添加矢量类定义

时间:2015-02-26 03:35:50

标签: python

我正在尝试在python中实现一个vector类,似乎无法弄清楚这个加法函数的逻辑。以下代码包含示例。

注意:Vec()是一个包含两个成员变量的类。 v.D设置向量的域,v.f是将域映射到相应值的字典。另请注意,v.D中映射到0的元素假设为v.f.

def add(u,v):
    """
    Returns the sum of the two vectors.
    Make sure to add together values for all keys from u.f and v.f even if
    some keys in u.f do not exist in v.f (or vice versa)

    >>> a = Vec({'a','e','i','o','u'}, {'a':0,'e':1,'i':2})
    >>> b = Vec({'a','e','i','o','u'}, {'o':4,'u':7})
    >>> c = Vec({'a','e','i','o','u'}, {'a':0,'e':1,'i':2,'o':4,'u':7})
    >>> a + b == c
    True
    >>> a == Vec({'a','e','i','o','u'}, {'a':0,'e':1,'i':2})
    True
    >>> b == Vec({'a','e','i','o','u'}, {'o':4,'u':7})
    True
    >>> d = Vec({'x','y','z'}, {'x':2,'y':1})
    >>> e = Vec({'x','y','z'}, {'z':4,'y':-1})
    >>> f = Vec({'x','y','z'}, {'x':2,'y':0,'z':4})
    >>> d + e == f
    True
    >>> b + Vec({'a','e','i','o','u'}, {}) == b
    True
    """
    assert u.D == v.D

    return Vec({v.D}, {x: v.f.get(x, 0) + u.f.get(x, 0) for x in v.D})

1 个答案:

答案 0 :(得分:3)

我的猜测是v.D是字典,所以这个

{v.D}

将等同于

{{...}}

这不是理想的。