Jesse Pet
Jesse Pet

Reputation: 1879

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?

Upvotes: 0

Views: 1225

Answers (3)

Sukrit Kalra
Sukrit Kalra

Reputation: 34531

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.

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

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

Upvotes: 3

zhangyangyu
zhangyangyu

Reputation: 8620

I think just implement a function such as equal is not the best choice. You can implement the __eq__ so you can use == to identify the similarity.

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

Upvotes: 1

jh314
jh314

Reputation: 27812

You can compare the fields:

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

Upvotes: 1

Related Questions