0

Ok so here is my class:

class Vec:
"""
A vector has two fields:
D - the domain (a set)
f - a dictionary mapping (some) domain elements to field elements
    elements of D not appearing in f are implicitly mapped to zero
"""
def __init__(self, labels, function):
    self.D = labels
    self.f = function

I need help creating a function that takes in two vectors, lets say:

u = Vec({'a','b','c'}, {'a':0,'c':1,'b':4})
v = Vec({'A','B','C'},{'A':1})

the function equal:

equal(u,v)

should return:

false

So far I've tried this:

v = Vec({'x','y','z'},{'y':1,'x':2})
u = Vec({'x','y','z'},{'y':1,'x':0})

def equal(u,v): 
    "Returns true iff u is equal to v" 
    assert u.D == v.D
    for d in v.f:
        for i in u.f:
            if v.f[d] == u.f[i]:
                return True 
            else:
                return False
print (equal(u,v))

I get true which is incorrect because it's only looking at the last value: 'y':1, how can I check for both?

4

3 回答 3

3

您尝试实施的方法已经为您完成。您可以使用集合相等和字典相等运算符。我要求您不要调用函数equal,而是使用__eq__允许==在类实例上使用的函数。

这是你可以做的

def __eq__(self, anotherInst):
    return self.D == anotherInst.D and self.f == anotherInst.f

阅读Python 文档__eq__中的方法

应用更改后试运行 -

>>> u = Vec({'a','b','c'}, {'a':0,'c':1,'b':4})
>>> v = Vec({'A','B','C'},{'A':1})
>>> u == v
False
于 2013-07-09T17:20:33.307 回答
1

您可以比较以下字段:

def equal(self, u, v):
    return u.D == v.D and u.f == v.f
于 2013-07-09T17:17:54.700 回答
1

我认为仅仅实现一个功能,例如equal不是最好的选择。您可以实现,__eq__以便您可以使用它==来识别相似性。

def __eq__(self, v):
    return self.D == v.D and self.f == v.f
于 2013-07-09T17:22:05.590 回答