简体   繁体   English

查找2个向量在python中是否相等

[英]Find if 2 vectors are equal in python

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? 我知道这是错误的,因为它仅查看最后一个值:'y':1,如何检查两者?

The method that you are trying to implement has already been done for you. 您要实现的方法已经为您完成。 You can use the set equality and the dictionary equality operator. 您可以使用集合相等性和字典相等性运算符。 I ask you not to make a function called equal and instead use __eq__ which allows the use of == on class instances. 我要求您不要制作一个称为equal的函数,而应使用__eq__ ,它允许在类实例上使用==

Here's what you can do 这是你可以做的

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

Read about the __eq__ method in the Python Docs 了解Python文档中__eq__方法

Test Run after applying the changes - 应用更改后进行测试运行-

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

You can compare the fields: 您可以比较以下字段:

def equal(self, u, v):
    return u.D == v.D and u.f == v.f

I think just implement a function such as equal is not the best choice. 我认为仅实现诸如equal的功能不是最佳选择。 You can implement the __eq__ so you can use == to identify the similarity. 您可以实现__eq__因此可以使用==标识相似性。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM