comparing values in two sets

Peter Otten __peter__ at web.de
Mon May 15 02:14:33 EDT 2006


Paul Rubin wrote:

> You could even get cutesy and say something like (untested):
> 
> from itertools import izip
> def test_sets(original_set, trans_letters):
>     return not sum(a==b for a,b in izip(original_set, trans_letters))
> 
> but that can be slower since it always scans both lists in entirety,
> even if a matching pair of elements is found right away.

Here's a variant that does performs only the necessary tests: 

>>> from itertools import izip
>>> True not in (a == b for a, b in izip(range(3), range(3)))
False

A "noisy" equality test to demonstrate short-circuiting behaviour:

>>> def print_eq(a, b):
...     print "%r == %r --> %r" % (a, b, a == b)
...     return a == b
...
>>> True not in (print_eq(a, b) for a, b in izip(range(3), range(3)))
0 == 0 --> True
False
>>> True not in (print_eq(a, b) for a, b in izip(["x", 1, 2], range(3)))
'x' == 0 --> False
1 == 1 --> True
False
>>> True not in (print_eq(a, b) for a, b in izip(["x", "x", "x"], range(3)))
'x' == 0 --> False
'x' == 1 --> False
'x' == 2 --> False
True

Peter




More information about the Python-list mailing list