Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: Retrieving an object from a set

Reply
Thread Tools

Re: Retrieving an object from a set

 
 
Ethan Furman
Guest
Posts: n/a
 
      01-25-2013
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~

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Retrieving an object from a set Arnaud Delobelle Python 1 01-26-2013 06:25 AM
Re: Retrieving an object from a set Dave Angel Python 0 01-25-2013 11:56 PM
Re: Retrieving an object from a set MRAB Python 0 01-25-2013 11:45 PM
Re: Retrieving an object from a set Ian Kelly Python 0 01-25-2013 11:37 PM
Re: Retrieving an object from a set Ian Kelly Python 0 01-25-2013 11:30 PM



Advertisments