/Lib/sets.py

http://unladen-swallow.googlecode.com/ · Python · 579 lines · 431 code · 33 blank · 115 comment · 47 complexity · dbf548bdfd04f191f47a2a9ddf8a3ee0 MD5 · raw file

  1. """Classes to represent arbitrary sets (including sets of sets).
  2. This module implements sets using dictionaries whose values are
  3. ignored. The usual operations (union, intersection, deletion, etc.)
  4. are provided as both methods and operators.
  5. Important: sets are not sequences! While they support 'x in s',
  6. 'len(s)', and 'for x in s', none of those operations are unique for
  7. sequences; for example, mappings support all three as well. The
  8. characteristic operation for sequences is subscripting with small
  9. integers: s[i], for i in range(len(s)). Sets don't support
  10. subscripting at all. Also, sequences allow multiple occurrences and
  11. their elements have a definite order; sets on the other hand don't
  12. record multiple occurrences and don't remember the order of element
  13. insertion (which is why they don't support s[i]).
  14. The following classes are provided:
  15. BaseSet -- All the operations common to both mutable and immutable
  16. sets. This is an abstract class, not meant to be directly
  17. instantiated.
  18. Set -- Mutable sets, subclass of BaseSet; not hashable.
  19. ImmutableSet -- Immutable sets, subclass of BaseSet; hashable.
  20. An iterable argument is mandatory to create an ImmutableSet.
  21. _TemporarilyImmutableSet -- A wrapper around a Set, hashable,
  22. giving the same hash value as the immutable set equivalent
  23. would have. Do not use this class directly.
  24. Only hashable objects can be added to a Set. In particular, you cannot
  25. really add a Set as an element to another Set; if you try, what is
  26. actually added is an ImmutableSet built from it (it compares equal to
  27. the one you tried adding).
  28. When you ask if `x in y' where x is a Set and y is a Set or
  29. ImmutableSet, x is wrapped into a _TemporarilyImmutableSet z, and
  30. what's tested is actually `z in y'.
  31. """
  32. # Code history:
  33. #
  34. # - Greg V. Wilson wrote the first version, using a different approach
  35. # to the mutable/immutable problem, and inheriting from dict.
  36. #
  37. # - Alex Martelli modified Greg's version to implement the current
  38. # Set/ImmutableSet approach, and make the data an attribute.
  39. #
  40. # - Guido van Rossum rewrote much of the code, made some API changes,
  41. # and cleaned up the docstrings.
  42. #
  43. # - Raymond Hettinger added a number of speedups and other
  44. # improvements.
  45. from __future__ import generators
  46. try:
  47. from itertools import ifilter, ifilterfalse
  48. except ImportError:
  49. # Code to make the module run under Py2.2
  50. def ifilter(predicate, iterable):
  51. if predicate is None:
  52. def predicate(x):
  53. return x
  54. for x in iterable:
  55. if predicate(x):
  56. yield x
  57. def ifilterfalse(predicate, iterable):
  58. if predicate is None:
  59. def predicate(x):
  60. return x
  61. for x in iterable:
  62. if not predicate(x):
  63. yield x
  64. try:
  65. True, False
  66. except NameError:
  67. True, False = (0==0, 0!=0)
  68. __all__ = ['BaseSet', 'Set', 'ImmutableSet']
  69. import warnings
  70. warnings.warn("the sets module is deprecated", DeprecationWarning,
  71. stacklevel=2)
  72. class BaseSet(object):
  73. """Common base class for mutable and immutable sets."""
  74. __slots__ = ['_data']
  75. # Constructor
  76. def __init__(self):
  77. """This is an abstract class."""
  78. # Don't call this from a concrete subclass!
  79. if self.__class__ is BaseSet:
  80. raise TypeError, ("BaseSet is an abstract class. "
  81. "Use Set or ImmutableSet.")
  82. # Standard protocols: __len__, __repr__, __str__, __iter__
  83. def __len__(self):
  84. """Return the number of elements of a set."""
  85. return len(self._data)
  86. def __repr__(self):
  87. """Return string representation of a set.
  88. This looks like 'Set([<list of elements>])'.
  89. """
  90. return self._repr()
  91. # __str__ is the same as __repr__
  92. __str__ = __repr__
  93. def _repr(self, sorted=False):
  94. elements = self._data.keys()
  95. if sorted:
  96. elements.sort()
  97. return '%s(%r)' % (self.__class__.__name__, elements)
  98. def __iter__(self):
  99. """Return an iterator over the elements or a set.
  100. This is the keys iterator for the underlying dict.
  101. """
  102. return self._data.iterkeys()
  103. # Three-way comparison is not supported. However, because __eq__ is
  104. # tried before __cmp__, if Set x == Set y, x.__eq__(y) returns True and
  105. # then cmp(x, y) returns 0 (Python doesn't actually call __cmp__ in this
  106. # case).
  107. def __cmp__(self, other):
  108. raise TypeError, "can't compare sets using cmp()"
  109. # Equality comparisons using the underlying dicts. Mixed-type comparisons
  110. # are allowed here, where Set == z for non-Set z always returns False,
  111. # and Set != z always True. This allows expressions like "x in y" to
  112. # give the expected result when y is a sequence of mixed types, not
  113. # raising a pointless TypeError just because y contains a Set, or x is
  114. # a Set and y contain's a non-set ("in" invokes only __eq__).
  115. # Subtle: it would be nicer if __eq__ and __ne__ could return
  116. # NotImplemented instead of True or False. Then the other comparand
  117. # would get a chance to determine the result, and if the other comparand
  118. # also returned NotImplemented then it would fall back to object address
  119. # comparison (which would always return False for __eq__ and always
  120. # True for __ne__). However, that doesn't work, because this type
  121. # *also* implements __cmp__: if, e.g., __eq__ returns NotImplemented,
  122. # Python tries __cmp__ next, and the __cmp__ here then raises TypeError.
  123. def __eq__(self, other):
  124. if isinstance(other, BaseSet):
  125. return self._data == other._data
  126. else:
  127. return False
  128. def __ne__(self, other):
  129. if isinstance(other, BaseSet):
  130. return self._data != other._data
  131. else:
  132. return True
  133. # Copying operations
  134. def copy(self):
  135. """Return a shallow copy of a set."""
  136. result = self.__class__()
  137. result._data.update(self._data)
  138. return result
  139. __copy__ = copy # For the copy module
  140. def __deepcopy__(self, memo):
  141. """Return a deep copy of a set; used by copy module."""
  142. # This pre-creates the result and inserts it in the memo
  143. # early, in case the deep copy recurses into another reference
  144. # to this same set. A set can't be an element of itself, but
  145. # it can certainly contain an object that has a reference to
  146. # itself.
  147. from copy import deepcopy
  148. result = self.__class__()
  149. memo[id(self)] = result
  150. data = result._data
  151. value = True
  152. for elt in self:
  153. data[deepcopy(elt, memo)] = value
  154. return result
  155. # Standard set operations: union, intersection, both differences.
  156. # Each has an operator version (e.g. __or__, invoked with |) and a
  157. # method version (e.g. union).
  158. # Subtle: Each pair requires distinct code so that the outcome is
  159. # correct when the type of other isn't suitable. For example, if
  160. # we did "union = __or__" instead, then Set().union(3) would return
  161. # NotImplemented instead of raising TypeError (albeit that *why* it
  162. # raises TypeError as-is is also a bit subtle).
  163. def __or__(self, other):
  164. """Return the union of two sets as a new set.
  165. (I.e. all elements that are in either set.)
  166. """
  167. if not isinstance(other, BaseSet):
  168. return NotImplemented
  169. return self.union(other)
  170. def union(self, other):
  171. """Return the union of two sets as a new set.
  172. (I.e. all elements that are in either set.)
  173. """
  174. result = self.__class__(self)
  175. result._update(other)
  176. return result
  177. def __and__(self, other):
  178. """Return the intersection of two sets as a new set.
  179. (I.e. all elements that are in both sets.)
  180. """
  181. if not isinstance(other, BaseSet):
  182. return NotImplemented
  183. return self.intersection(other)
  184. def intersection(self, other):
  185. """Return the intersection of two sets as a new set.
  186. (I.e. all elements that are in both sets.)
  187. """
  188. if not isinstance(other, BaseSet):
  189. other = Set(other)
  190. if len(self) <= len(other):
  191. little, big = self, other
  192. else:
  193. little, big = other, self
  194. common = ifilter(big._data.has_key, little)
  195. return self.__class__(common)
  196. def __xor__(self, other):
  197. """Return the symmetric difference of two sets as a new set.
  198. (I.e. all elements that are in exactly one of the sets.)
  199. """
  200. if not isinstance(other, BaseSet):
  201. return NotImplemented
  202. return self.symmetric_difference(other)
  203. def symmetric_difference(self, other):
  204. """Return the symmetric difference of two sets as a new set.
  205. (I.e. all elements that are in exactly one of the sets.)
  206. """
  207. result = self.__class__()
  208. data = result._data
  209. value = True
  210. selfdata = self._data
  211. try:
  212. otherdata = other._data
  213. except AttributeError:
  214. otherdata = Set(other)._data
  215. for elt in ifilterfalse(otherdata.has_key, selfdata):
  216. data[elt] = value
  217. for elt in ifilterfalse(selfdata.has_key, otherdata):
  218. data[elt] = value
  219. return result
  220. def __sub__(self, other):
  221. """Return the difference of two sets as a new Set.
  222. (I.e. all elements that are in this set and not in the other.)
  223. """
  224. if not isinstance(other, BaseSet):
  225. return NotImplemented
  226. return self.difference(other)
  227. def difference(self, other):
  228. """Return the difference of two sets as a new Set.
  229. (I.e. all elements that are in this set and not in the other.)
  230. """
  231. result = self.__class__()
  232. data = result._data
  233. try:
  234. otherdata = other._data
  235. except AttributeError:
  236. otherdata = Set(other)._data
  237. value = True
  238. for elt in ifilterfalse(otherdata.has_key, self):
  239. data[elt] = value
  240. return result
  241. # Membership test
  242. def __contains__(self, element):
  243. """Report whether an element is a member of a set.
  244. (Called in response to the expression `element in self'.)
  245. """
  246. try:
  247. return element in self._data
  248. except TypeError:
  249. transform = getattr(element, "__as_temporarily_immutable__", None)
  250. if transform is None:
  251. raise # re-raise the TypeError exception we caught
  252. return transform() in self._data
  253. # Subset and superset test
  254. def issubset(self, other):
  255. """Report whether another set contains this set."""
  256. self._binary_sanity_check(other)
  257. if len(self) > len(other): # Fast check for obvious cases
  258. return False
  259. for elt in ifilterfalse(other._data.has_key, self):
  260. return False
  261. return True
  262. def issuperset(self, other):
  263. """Report whether this set contains another set."""
  264. self._binary_sanity_check(other)
  265. if len(self) < len(other): # Fast check for obvious cases
  266. return False
  267. for elt in ifilterfalse(self._data.has_key, other):
  268. return False
  269. return True
  270. # Inequality comparisons using the is-subset relation.
  271. __le__ = issubset
  272. __ge__ = issuperset
  273. def __lt__(self, other):
  274. self._binary_sanity_check(other)
  275. return len(self) < len(other) and self.issubset(other)
  276. def __gt__(self, other):
  277. self._binary_sanity_check(other)
  278. return len(self) > len(other) and self.issuperset(other)
  279. # Assorted helpers
  280. def _binary_sanity_check(self, other):
  281. # Check that the other argument to a binary operation is also
  282. # a set, raising a TypeError otherwise.
  283. if not isinstance(other, BaseSet):
  284. raise TypeError, "Binary operation only permitted between sets"
  285. def _compute_hash(self):
  286. # Calculate hash code for a set by xor'ing the hash codes of
  287. # the elements. This ensures that the hash code does not depend
  288. # on the order in which elements are added to the set. This is
  289. # not called __hash__ because a BaseSet should not be hashable;
  290. # only an ImmutableSet is hashable.
  291. result = 0
  292. for elt in self:
  293. result ^= hash(elt)
  294. return result
  295. def _update(self, iterable):
  296. # The main loop for update() and the subclass __init__() methods.
  297. data = self._data
  298. # Use the fast update() method when a dictionary is available.
  299. if isinstance(iterable, BaseSet):
  300. data.update(iterable._data)
  301. return
  302. value = True
  303. if type(iterable) in (list, tuple, xrange):
  304. # Optimized: we know that __iter__() and next() can't
  305. # raise TypeError, so we can move 'try:' out of the loop.
  306. it = iter(iterable)
  307. while True:
  308. try:
  309. for element in it:
  310. data[element] = value
  311. return
  312. except TypeError:
  313. transform = getattr(element, "__as_immutable__", None)
  314. if transform is None:
  315. raise # re-raise the TypeError exception we caught
  316. data[transform()] = value
  317. else:
  318. # Safe: only catch TypeError where intended
  319. for element in iterable:
  320. try:
  321. data[element] = value
  322. except TypeError:
  323. transform = getattr(element, "__as_immutable__", None)
  324. if transform is None:
  325. raise # re-raise the TypeError exception we caught
  326. data[transform()] = value
  327. class ImmutableSet(BaseSet):
  328. """Immutable set class."""
  329. __slots__ = ['_hashcode']
  330. # BaseSet + hashing
  331. def __init__(self, iterable=None):
  332. """Construct an immutable set from an optional iterable."""
  333. self._hashcode = None
  334. self._data = {}
  335. if iterable is not None:
  336. self._update(iterable)
  337. def __hash__(self):
  338. if self._hashcode is None:
  339. self._hashcode = self._compute_hash()
  340. return self._hashcode
  341. def __getstate__(self):
  342. return self._data, self._hashcode
  343. def __setstate__(self, state):
  344. self._data, self._hashcode = state
  345. class Set(BaseSet):
  346. """ Mutable set class."""
  347. __slots__ = []
  348. # BaseSet + operations requiring mutability; no hashing
  349. def __init__(self, iterable=None):
  350. """Construct a set from an optional iterable."""
  351. self._data = {}
  352. if iterable is not None:
  353. self._update(iterable)
  354. def __getstate__(self):
  355. # getstate's results are ignored if it is not
  356. return self._data,
  357. def __setstate__(self, data):
  358. self._data, = data
  359. # We inherit object.__hash__, so we must deny this explicitly
  360. __hash__ = None
  361. # In-place union, intersection, differences.
  362. # Subtle: The xyz_update() functions deliberately return None,
  363. # as do all mutating operations on built-in container types.
  364. # The __xyz__ spellings have to return self, though.
  365. def __ior__(self, other):
  366. """Update a set with the union of itself and another."""
  367. self._binary_sanity_check(other)
  368. self._data.update(other._data)
  369. return self
  370. def union_update(self, other):
  371. """Update a set with the union of itself and another."""
  372. self._update(other)
  373. def __iand__(self, other):
  374. """Update a set with the intersection of itself and another."""
  375. self._binary_sanity_check(other)
  376. self._data = (self & other)._data
  377. return self
  378. def intersection_update(self, other):
  379. """Update a set with the intersection of itself and another."""
  380. if isinstance(other, BaseSet):
  381. self &= other
  382. else:
  383. self._data = (self.intersection(other))._data
  384. def __ixor__(self, other):
  385. """Update a set with the symmetric difference of itself and another."""
  386. self._binary_sanity_check(other)
  387. self.symmetric_difference_update(other)
  388. return self
  389. def symmetric_difference_update(self, other):
  390. """Update a set with the symmetric difference of itself and another."""
  391. data = self._data
  392. value = True
  393. if not isinstance(other, BaseSet):
  394. other = Set(other)
  395. if self is other:
  396. self.clear()
  397. for elt in other:
  398. if elt in data:
  399. del data[elt]
  400. else:
  401. data[elt] = value
  402. def __isub__(self, other):
  403. """Remove all elements of another set from this set."""
  404. self._binary_sanity_check(other)
  405. self.difference_update(other)
  406. return self
  407. def difference_update(self, other):
  408. """Remove all elements of another set from this set."""
  409. data = self._data
  410. if not isinstance(other, BaseSet):
  411. other = Set(other)
  412. if self is other:
  413. self.clear()
  414. for elt in ifilter(data.has_key, other):
  415. del data[elt]
  416. # Python dict-like mass mutations: update, clear
  417. def update(self, iterable):
  418. """Add all values from an iterable (such as a list or file)."""
  419. self._update(iterable)
  420. def clear(self):
  421. """Remove all elements from this set."""
  422. self._data.clear()
  423. # Single-element mutations: add, remove, discard
  424. def add(self, element):
  425. """Add an element to a set.
  426. This has no effect if the element is already present.
  427. """
  428. try:
  429. self._data[element] = True
  430. except TypeError:
  431. transform = getattr(element, "__as_immutable__", None)
  432. if transform is None:
  433. raise # re-raise the TypeError exception we caught
  434. self._data[transform()] = True
  435. def remove(self, element):
  436. """Remove an element from a set; it must be a member.
  437. If the element is not a member, raise a KeyError.
  438. """
  439. try:
  440. del self._data[element]
  441. except TypeError:
  442. transform = getattr(element, "__as_temporarily_immutable__", None)
  443. if transform is None:
  444. raise # re-raise the TypeError exception we caught
  445. del self._data[transform()]
  446. def discard(self, element):
  447. """Remove an element from a set if it is a member.
  448. If the element is not a member, do nothing.
  449. """
  450. try:
  451. self.remove(element)
  452. except KeyError:
  453. pass
  454. def pop(self):
  455. """Remove and return an arbitrary set element."""
  456. return self._data.popitem()[0]
  457. def __as_immutable__(self):
  458. # Return a copy of self as an immutable set
  459. return ImmutableSet(self)
  460. def __as_temporarily_immutable__(self):
  461. # Return self wrapped in a temporarily immutable set
  462. return _TemporarilyImmutableSet(self)
  463. class _TemporarilyImmutableSet(BaseSet):
  464. # Wrap a mutable set as if it was temporarily immutable.
  465. # This only supplies hashing and equality comparisons.
  466. def __init__(self, set):
  467. self._set = set
  468. self._data = set._data # Needed by ImmutableSet.__eq__()
  469. def __hash__(self):
  470. return self._set._compute_hash()