drunkenmonkey44
drunkenmonkey44

Reputation: 51

Comparing Equality of Vectors as a Dictionary

So I have a problem to solve (outlined below). This question makes use of a class (Vec) that has two member variables. v.D refers to elements in the domain of a vector, while v.f refers to a dictionary that maps domain elements.

For example, if v = Vec({'x','y','z'},{'y':1,'x':2}) then v.D = {'x', 'y', 'z'} and v.f = {'y':1, x:'2'}. If an element of v.D does not appear in v.f it is assumed that element of the domain is mapped to zero (i.e. 'z':0 appears in v.D but is only assumed to be in v.f).

The question recommends I use the all() attribute, but I cannot seem to make it work.I included two solutions below (both of which will not work). The main problem I am having is testing for equality when elements of v.D do not appear with keys in v.f

`

def equal(u,v):

""" Return true iff u is equal to v (where u and v are members of class vec()). Because of sparse representation (domain mapped to zero), it is not enough to compare dictionaries

>>> Vec({'a', 'b', 'c'}, {'a':0}) == Vec({'a', 'b', 'c'}, {'b':0})
True

Be sure that equal(u, v) check equalities 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)

>>> Vec({'x','y','z'},{'y':1,'x':2}) == Vec({'x','y','z'},{'y':1,'z':0})
False
>>> Vec({'a','b','c'}, {'a':0,'c':1}) == Vec({'a','b','c'}, {'a':0,'c':1,'b':4})
False
>>> Vec({'a','b','c'}, {'a':0,'c':1,'b':4}) == Vec({'a','b','c'}, {'a':0,'c':1})
False

The keys matter:
>>> Vec({'a','b'},{'a':1}) == Vec({'a','b'},{'b':1})
False

The values matter:
>>> Vec({'a','b'},{'a':1}) == Vec({'a','b'},{'a':2})
False

"""


assert u.D == v.D

for k in v.D:
    if k in v.f and k in u.f:
        return v.f[k] == u.f[k]

all(v.f[i] == u.f[i] for i in v.D)

'

Upvotes: 1

Views: 58

Answers (1)

Alex Martelli
Alex Martelli

Reputation: 882851

I would do it as follows:

def equal(u, v):
   if u.D != v.D: return False  # domains must be equal
   return all(u.f.get(x, 0) == v.f.get(x, 0) for x in u.D)

Anything wrong with this obvious solution?

Upvotes: 4

Related Questions