[Python-ideas] exclusively1, common, exclusively2 = set1 - set2, set1 & set2, set2 - set1

Oscar Benjamin oscar.j.benjamin at gmail.com
Thu Jul 4 16:33:04 CEST 2013


On 4 July 2013 03:10, Steven D'Aprano <steve at pearwood.info> wrote:
>
>> I also wondered that if such an algorithm existed, would it be useful
>> enough to be worth incorporating into the Python library?
>>
>> Maybe defined as:
>>
>> exclusively1, common, exclusively2 = set1.partition(set2)
>
> [bikeshed]
> I would expect common, only1, only2 in that order.

I like the other order. It reads like a horizontal Venn diagram e.g.:
http://upload.wikimedia.org/wikipedia/commons/9/99/Venn0001.svg

Although it probably wouldn't be the best order if the function were
somehow generalised to more than two sets (not that I can think of a
useful and intelligible generalisation).

> Does any other language with sets offer this as a set primitive?

I'd be interested to know what they call it if they do. "Partition"
seems wrong to me. If a set had a partition method I would expect it
give me a partition of that set i.e. a set of disjoint subsets
covering the original set. This is related to the partition of the set
in the sense that if

    xonly, xandy, yonly = set.partition(setx, sety)

then {xonly, xandy} is a partition of setx and {yonly, xandy} is a
partition of sety and {xonly, xandy, yonly} is a partition of the
union setx | sety. I think, though, that I would expect a
set.partition method to work something like

    true_set, false_set = setx.partition(lambda x: predicate(x))

with the obvious semantics. Then you could get a single pass algorithm
for the original problem with

    xandy, xonly = setx.partition(sety.__contains__)
    yonly = sety - xandy


Oscar


More information about the Python-ideas mailing list