comparing values in two sets
Gerard Flanagan
grflanagan at yahoo.co.uk
Mon May 15 13:25:43 CEST 2006
Gerard Flanagan wrote:
> 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 ):
> return True not in ( val == L2[idx] for idx, val in enumerate(L1) )
>
> assert are_itemwise_different(s1,s2)
> assert not are_itemwise_different(s1,s3)
> assert are_itemwise_different(s1,s4)
>
s1 = 'abcd'
s2 = 'zzzz'
s3 = 'zbzz'
s4 = 'zzbz'
s5 = 'xbxx'
def itemwise_intersect( L1, L2 ):
return [value for idx, value in set(enumerate(L1)) &
set(enumerate(L2))]
assert itemwise_intersect(s1,s2) == []
assert itemwise_intersect(s1,s3) == ['b']
assert itemwise_intersect(s1,s4) == []
def itemwise_intersect( *args ):
s = set(enumerate(args[0]))
for t in ( set(enumerate(X)) for X in args[1:]):
s.intersection_update(t)
return [val for i,val in s]
assert itemwise_intersect(s1,s3,s5) == ['b']
Gerard
More information about the Python-list
mailing list