I have a use-case for an efficient implementation of a Set with XOR-like behaviour.
A set that, if an element is added, removes the element from the set if it is already contained in the set, but adds it in case it is not. See the below code:
# Create set `a`
a = xorset((0,0,0,1,1,2))
assert a == {0,2}
a.add(0)
assert a == {2}
a.add(0)
assert a == {0,2}
a.update((0,0))
assert a == {0,2}
a.update((0,0,0,2,1))
assert a == {1}
My best attempt so far has been to use the collections Counter object to create sets like so:
from collections import Counter
def xorset(it):
return set(k for k,v in Counter(it) if v % 2 == 1)
and then to manually implement the add & update operations:
import itertools
def xorset_add(s,e):
if e in s:
s.remove(e)
else:
s.add(e)
return s # not necessary as works in place
def xorset_update(s,it):
return set(k for k,v in Counter(itertools.chain(s,it)) if v % 2 == 1)
I would imagine there'd be significant speed-ups possible if there was a lib that handled the addition/removal of new elements, but I have not been able to find any. Does anyone know of the existence of one?
Thanks!