comparing values in two sets

John Machin sjmachin at lexicon.net
Mon May 15 01:41:19 CEST 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.

There is no such concept as "position in [a] set". Sets in
math[s]/logic are *NOT* ordered. The order in which Python retrieves
elements when you do (for example)  list(a_set) is a meaningless
artefact of the implementation du jour, and is not to be relied on.

>>> s = set(['xyzzy', 'plugh', 'sesame'])
>>> t = set(['xyzzy', 'plugh', 'mellon'])
>>> s
set(['sesame', 'plugh', 'xyzzy'])
>>> t
set(['plugh', 'mellon', 'xyzzy'])
>>> zip(s, t)
[('sesame', 'plugh'), ('plugh', 'mellon'), ('xyzzy', 'xyzzy')]
>>>

You may need one or more of these:
>>> s & t
set(['plugh', 'xyzzy'])
>>> s ^ t
set(['sesame', 'mellon'])
>>> s | t
set(['sesame', 'plugh', 'mellon', 'xyzzy'])
>>> (s | t) - t
set(['sesame'])
>>> (s | t) - s
set(['mellon'])
>>>

If that doesn't meet your needs:
     back up a level and tell us what you are trying to achieve

If True:
    read about sets in the Python docs

HTH,
John




More information about the Python-list mailing list