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

Peter Otten __peter__ at web.de
Thu Jul 4 09:14:00 CEST 2013


Oscar Benjamin wrote:
> On 3 July 2013 21:50, Paddy3118
> <paddy3118 at gmail.com> wrote:
>> I found myself repeating something that I know I have used before,
>> several times: I get two sets of results, may be sets of the passing
>> tests when a design has changed, and I need to work out what has changed
>> so work out
>>>> 1. What passed first time round
>> 2. What passed both times.
>> 3. What passed only the second time round.
>>>> I usually use something like the set equations in the title to do this
>> but I recognise that this requires both sets to be traversed at least
>> three times which seems wasteful.
>>>> I wondered if their was am algorithm to partition the two sets of data
>> into three as above, but cutting down on the number of set traversals?
>> You can do it in one traversal of each set:
>> def partition(setx, sety):
> xonly, xandy, yonly = set(), set(), set()
> for set1, set2, setn in [(setx, sety, xonly), (sety, setx, yonly)]:
> for val in set1:
> if val in set2:
> xandy.add(val)
> else:
> setn.add(val)
> return xonly, xandy, yonly

The price you pay for the symmetry is that for the second iteration of the 
outer loop 
xandy.add(val)
is a noop. When you give up that symmetry you can replace one inner loop 
with a set operation:
def partition(old, new):
 removed = old - new
 common = set()
 added = set()
 for item in new:
 if item in old:
 common.add(item)
 else:
 added.add(item)
 return removed, common, added


More information about the Python-ideas mailing list

AltStyle によって変換されたページ (->オリジナル) /