Created
April 22, 2020 02:26
-
-
Save ivirshup/8a76df55a461563deb15f185f427f2e5 to your computer and use it in GitHub Desktop.
OrderedSet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Simple OrderedSet implementation.""" | |
from collections import OrderedDict | |
from collections.abc import MutableSet | |
from functools import reduce | |
from itertools import repeat | |
from operator import or_, sub | |
class OrderedSet(MutableSet): | |
"""Set that maintains insertion order.""" | |
def __init__(self, vals=()): | |
self.dict = OrderedDict(zip(vals, repeat(None))) | |
def __contains__(self, val): | |
return val in self.dict | |
def __iter__(self): | |
return iter(self.dict) | |
def __len__(self): | |
return len(self.dict) | |
def __repr__(self): | |
return "OrderedSet: {" + ", ".join(map(str, self)) + "}" | |
def copy(self): | |
return OrderedSet(self.dict.copy()) | |
def add(self, val): | |
self.dict[val] = None | |
def union(self, *vals): | |
return reduce(or_, vals, self) | |
def discard(self, val): | |
if val in self: | |
del self.dict[val] | |
def difference(self, *vals): | |
return reduce(sub, vals, self) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment