[Python-ideas] universal set object for use in set manipulation

Andy Kish agkish at gmail.com
Thu Jul 23 09:55:41 CEST 2009


If we want to go golfing :), my favorite solution is with the python
2.6 versions of intersection and union:

    set_union = set().union(*sets)
    set_intersection = set.universal().intersection(*sets)

Folds are nice. That's actually why I sent my initial email to the
list. It's really annoying to having appropriate identity element for
union built in while missing the *correct* identity element for
intersection.

Andy.

On Jul 23, 3:12 am, Andrew Bennetts <and... at bemusement.org> wrote:
> Andy Kish wrote:
>
> [...]
>
>
>
> > The above intersection case would end up looking something like:
>
> >     set_intersection = set.universal()
> >     for s in sets:
> >         set_intersection &= s
>
> Or even:
>
>    set_intersection = reduce(operator.and_, sets, set.universal())
>
> Although, you can already pass multiple (or zero) sets to set.intersection().
> So your special case version can be a little simpler...
>
>    sets = list(sets)
>    if len(sets) == 0:
>        return set()
>    return sets[0].intersection(sets[1:])
>
> Which isn't as elegant, but it's also not so bad.  
>
> -Andrew.
>
> _______________________________________________
> Python-ideas mailing list
> Python-id... at python.orghttp://mail.python.org/mailman/listinfo/python-ideas



More information about the Python-ideas mailing list