Skip to content

Instantly share code, notes, and snippets.

@kurtbrose
Last active November 3, 2018 00:32
Show Gist options
  • Select an option

  • Save kurtbrose/29ae67bf21cad289a8ad980d07a6ff24 to your computer and use it in GitHub Desktop.

Select an option

Save kurtbrose/29ae67bf21cad289a8ad980d07a6ff24 to your computer and use it in GitHub Desktop.
an inverse set
class ComplementSet(object):
'''
inverse of a normal set -- everything except the set is in there
'''
def __init__(self, missing):
assert type(missing) in (set, frozenset)
self.missing = missing
def __repr__(self): return 'ComplementSet({' + ', '.join([repr(e) for e in self.missing]) + '})'
def __contains__(self, item):
return not item in self.missing
def add(self, item):
if item in self.missing:
self.missing.remove(item)
def remove(self, item):
self.missing.add(item)
def intersection(self, other):
if type(other) in (set, frozenset):
return other - self.missing
if type(other) is ComplementSet:
return ComplementSet(self.missing.union(other.missing))
raise TypeError()
def union(self, other):
if type(other) in (set, frozenset):
return ComplementSet(self.missing - other)
if type(other) is ComplementSet:
return ComplementSet(self.missing.intersection(other.missing))
raise TypeError()
def symmetric_difference(self, other):
if type(other) in (set, frozenset):
return ComplementSet(self.missing.union(other))
if type(other) is ComplementSet:
return self.missing.symmetric_difference(other.missing)
raise TypeError()
def isdisjoint(self, other):
if type(other) in (set, frozenset):
return other.issubset(self.missing)
if type(other) is ComplementSet:
return False
raise TypeError()
def issubset(self, other):
'''everything missing from other is also missing from self'''
if type(other) in (set, frozenset):
return False
if type(other) is ComplementSet:
return self.missing.issupserset(other.missing)
raise TypeError()
def issuperset(self, other):
'''everything missing from self is also missing from super'''
if type(other) in (set, frozenset):
return not self.missing.intersection(other)
if type(other) is ComplementSet:
return self.missing.issubset(other.missing)
raise TypeError()
def __eq__(self, other):
return type(self) is type(other) and self.missing == other.missing
def __hash__(self):
return hash(self.missing)
def __len__(self):
raise NotImplemented # float('inf') - len(self.missing)
def test():
assert ComplementSet({1, 2}).union({1, 2}) == ComplementSet(set())
everything = ComplementSet(frozenset())
assert everything in everything # https://en.wikipedia.org/wiki/Russell%27s_paradox
if __name__ == "__main__":
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment