Py2.3: Feedback on Sets (fwd)

Raymond Hettinger vze4rx4y at verizon.net
Sun Aug 17 12:28:38 EDT 2003


"Alex Martelli" <aleaxit at yahoo.com> wrote in message
news:bhntvc01enr at enews1.newsguy.com...
> David Mertz wrote:
>    ...
> > Raymond Hettinger also wrote:
> > |from sets import Set
> > |def powerset(iterable):
> > |    data = list(iterable)
> > |    for i in xrange(2**len(data)):
> > |        yield Set([e for j,e in enumerate(data) if i&(1<<j)])
> >
> > Hmmm...  I should have checked the docs first.  A sample implementation
> > obviously helps.  That said, this isn't REALLY an implementation of
> > powerset.  It returns an iterator, not a set.  Now, sure... an iterator
> > is a BETTER thing to get, for lots of reasons.  But I'm not sure it
> > lives up to the function name.
>
> Surely writing
>
> def therealpowerset(iterable):
>     return Set(powerset(iterable))
>
> (or just inlining the Set call) isn't beyond the abilities of most
> prospective users.  Just like one calls list(x) on any iterable x
> if one needs specifically a list, so does one call Set(x) if one
> needs specifically a set.  Sure, the name is debatable, and maybe
> 'subsetsof' would be neater.  But I think this is quibbling.
>
> IMHO, one 'real' issue with this function is that it behaves strangely
> (to me) when iterable has duplicated elements -- namely, the
> resulting iterator also has duplications.  Changing the single
> statement that is currently:
>     data = list(iterable)
> into
>     data = Set(iterable)
> would make duplications in 'iterable' irrelevant instead.

Good call.
Do you guys want the revised version added to the docs
or perhaps saved as an ASPN recipe?

>>> from sets import Set
>>> def powersetiterator(iterable):
...     data = Set(iterable)
...     for i in xrange(2**len(data)):
...         yield Set([e for j,e in enumerate(data) if i&(1<<j)])

>>> Set(powersetiterator('abc'))
Set([ImmutableSet([]), ImmutableSet(['a']), ImmutableSet(['c']),
ImmutableSet(['b']), ImmutableSet(['c', 'b']), ImmutableSet(['a', 'c']),
ImmutableSet(['a', 'b']), ImmutableSet(['a', 'c', 'b'])])


Raymond Hettinger






More information about the Python-list mailing list