ordered_set.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import collections
  2. class OrderedSet(collections.MutableSet):
  3. def __init__(self, iterable=None):
  4. self.end = end = []
  5. end += [None, end, end] # sentinel node for doubly linked list
  6. self.map = {} # key --> [key, prev, next]
  7. if iterable is not None:
  8. self |= iterable
  9. def __len__(self):
  10. return len(self.map)
  11. def __contains__(self, key):
  12. return key in self.map
  13. def add(self, key):
  14. if key not in self.map:
  15. end = self.end
  16. curr = end[1]
  17. curr[2] = end[1] = self.map[key] = [key, curr, end]
  18. def discard(self, key):
  19. if key in self.map:
  20. key, prev, next = self.map.pop(key)
  21. prev[2] = next
  22. next[1] = prev
  23. def __iter__(self):
  24. end = self.end
  25. curr = end[2]
  26. while curr is not end:
  27. yield curr[0]
  28. curr = curr[2]
  29. def __reversed__(self):
  30. end = self.end
  31. curr = end[1]
  32. while curr is not end:
  33. yield curr[0]
  34. curr = curr[1]
  35. def pop(self, last=True):
  36. if not self:
  37. raise KeyError('set is empty')
  38. key = self.end[1][0] if last else self.end[2][0]
  39. self.discard(key)
  40. return key
  41. def __repr__(self):
  42. if not self:
  43. return '%s()' % (self.__class__.__name__,)
  44. return '%s(%r)' % (self.__class__.__name__, list(self))
  45. def __eq__(self, other):
  46. if isinstance(other, OrderedSet):
  47. return len(self) == len(other) and list(self) == list(other)
  48. return set(self) == set(other)