Can't get items out of a set?

Cruxic cruxic at gmail.com
Sat Mar 8 17:28:29 CET 2008


On Mar 8, 7:32 am, Alan Isaac <ais... at american.edu> wrote:
> Cruxic wrote:
> > people = set( [Person(1, 'Joe'), Person(2, 'Sue')] )
> > ...
> > p = people.get_equivalent(2)  #method doesn't exist as far as I know
> > print p.name  #prints Sue
>
> def get_equivalent(test, container):
>
>   for p in container:
>
>     if p == test:
>
>       return p
>
> hth,
>
> Alan Isaac
>
> #example (note change in __eq__ to match your case; fix if nec)
>
> class Person:
>
>   def __init__(self, id, name):
>
>     self.id = id
>
>     self.name = name
>
>   def __hash__(self):
>
>     return self.id
>
>   def __eq__(self, other):
>
>     return self.id == other
>
> people = set( [Person(1, 'Joe'), Person(2, 'Sue')] )
>
> get_equivalent(2,people)

That works fine for small data sets but my goal is to avoid a linear
search, instead leveraging the O(1) lookup time for a hash based set.



More information about the Python-list mailing list