comparing values in two sets
Paul Rubin
http
Sun May 14 20:38:39 EDT 2006
John Salerno <johnjsal at NOSPAMgmail.com> writes:
> 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 think by "sets" you mean "lists". Sets are unordered, as a few
people have mentioned.
> 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
That's fairly reasonable. You could use itertools.izip instead of
zip, which makes a generator instead of building up a whole new list
in memory. A more traditional imperative-style version would be
something like:
def test_sets(original_set, trans_letters):
for i in xrange(len(original_set)):
if original_set[i] == trans_letters[i]:
return True
return False
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.
I don't offhand see a builtin function or not-too-obscure one-liner
that short-circuits, but maybe there is one.
Note that all the above examples assume the two lists are the same
length. Otherwise, some adjustment is needed.
More information about the Python-list
mailing list