Re: Retrieving an object from a set

Discussion in 'Python' started by Ethan Furman, Jan 25, 2013.

  1. Ethan Furman

    Ethan Furman Guest

    On 01/25/2013 03:14 PM, Arnaud Delobelle wrote:
    > I've got a seemingly simple problem, but for which I cannot find a
    > simple solution.
    >
    > I have a set of objects (say S) containing an object which is equal to
    > a given object (say x). So
    >
    > x in S
    >
    > is true. So there is an object y in S which is equal to x. My
    > problem is how to retrieve y, without going through the whole set.
    > Here is a simple illustration with tuples (my actual scenario is not
    > with tuples but with a custom class):
    >
    >>>> y = (1, 2, 3) # This is the 'hidden object'
    >>>> S = set([y] + range(10000))
    >>>> x = (1, 2, 3)
    >>>> x in S

    > True
    >>>> x is y

    > False
    >
    > I haven't found y. It's a very simple problem, and this is the
    > simplest solution I can think of:
    >
    > class FindEqual(object):
    > def __init__(self, obj):
    > self.obj = obj
    > def __hash__(self):
    > return hash(self.obj)
    > def __eq__(self, other):
    > equal = self.obj == other
    > if equal:
    > self.lastequal = other
    > return equal
    >
    >>>> yfinder = FindEqual(x)
    >>>> yfinder in S

    > True
    >>>> yfinder.lastequal is y

    > True
    >
    > I've found y! I'm not happy with this as it really is a trick. Is
    > there a cleaner solution?


    I don't know if there is a cleaner solution, and I quite like yours.

    Can you tell us, though, why you have to have y if x == y? Is there
    some subtle difference between the two equal objects?

    ~Ethan~
    Ethan Furman, Jan 25, 2013
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Arnaud Delobelle

    Retrieving an object from a set

    Arnaud Delobelle, Jan 25, 2013, in forum: Python
    Replies:
    1
    Views:
    111
    Steven D'Aprano
    Jan 26, 2013
  2. Ian Kelly

    Re: Retrieving an object from a set

    Ian Kelly, Jan 25, 2013, in forum: Python
    Replies:
    0
    Views:
    109
    Ian Kelly
    Jan 25, 2013
  3. Ian Kelly

    Re: Retrieving an object from a set

    Ian Kelly, Jan 25, 2013, in forum: Python
    Replies:
    0
    Views:
    100
    Ian Kelly
    Jan 25, 2013
  4. MRAB
    Replies:
    0
    Views:
    108
  5. Dave Angel

    Re: Retrieving an object from a set

    Dave Angel, Jan 25, 2013, in forum: Python
    Replies:
    0
    Views:
    112
    Dave Angel
    Jan 25, 2013
Loading...

Share This Page