comparing values in two sets

Gerard Flanagan grflanagan at yahoo.co.uk
Mon May 15 04:35:27 EDT 2006


John Salerno wrote:
> I'd like to compare the values in two different sets to test if any of
> the positions in either set share the same value (e.g., if the third
> element of each set is an 'a', then the test fails).
>
> I have this:
>
> def test_sets(original_set, trans_letters):
>      for pair in zip(original_set, trans_letters):
>          if pair[0] == pair[1]:
>              return False
>      return True
>
>
> zip() was the first thing I thought of, but I was wondering if there's
> some other way to do it, perhaps a builtin that actually does this kind
> of testing.
>
> Thanks.

'enumerate' is another possibility:

s1 = 'abcd'
s2 = 'zzzz'
s3 = 'zbzz'
s4 = 'zzbz'

def are_itemwise_different( L1, L2 ):
    #if len(L1) != len(L2): return True
    for idx, value in enumerate(L1):
        if value == L2[idx]:
            return False
    return True

#after Peter Otten
def are_itemwise_different( L1, L2 ):
    #if len(L1) != len(L2): return True
    return True not in ( value == L2[idx] for idx, value in
enumerate(L1) )

assert are_itemwise_different(s1,s2)
assert not are_itemwise_different(s1,s3)
assert are_itemwise_different(s1,s4)

def itemwise_intersect( L1, L2 ):
    #if len(L1) != len(L2): raise
    for idx, value in enumerate(L1):
        if value == L2[idx]:
            yield value

assert list(itemwise_intersect(s1,s2)) == []
assert list(itemwise_intersect(s1,s3)) == ['b']
assert list(itemwise_intersect(s1,s4)) == []  

Gerard




More information about the Python-list mailing list