Debian Codegraph @

collections_extended/setlists.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 """Setlist class definitions."""
2 import random as random_
3 from collections.abc import (
4 Hashable,
5 MutableSequence,
6 MutableSet,
7 Sequence,
8 Set,
9 )
10
11 from . import _util
12
13 __all__ = ('SetList', 'setlist', 'frozensetlist')
14
15
16 class SetList(Sequence, Set):
17 """A setlist is an ordered `Collection` of unique elements.
18
19 `SetList` is the superclass of `setlist` and `frozensetlist`. It is
20 immutable and unhashable.
21 """
22
23 def __init__(self, iterable=None, raise_on_duplicate=False):
24 """Create a setlist, initializing from iterable if present.
25
26 Args:
27 iterable (Iterable): Values to initialize the setlist with.
28 raise_on_duplicate: Raise a ValueError if any duplicate values
29 are present.
30 """
31 self._list = list()
32 self._dict = dict()
33 if iterable:
34 if raise_on_duplicate:
35 self._extend(iterable)
36 else:
37 self._update(iterable)
38
39 def __repr__(self):
40 if len(self) == 0:
41 return '{0}()'.format(self.__class__.__name__)
42 else:
43 repr_format = '{class_name}({values!r})'
44 return repr_format.format(
45 class_name=self.__class__.__name__,
46 values=tuple(self),
47 )
48
49 # Convenience methods
50
51 def _fix_neg_index(self, index):
52 if index < 0:
53 index += len(self)
54 if index < 0:
55 raise IndexError('index is out of range')
56 return index
57
58 def _fix_end_index(self, index):
59 if index is None:
60 return len(self)
61 else:
62 return self._fix_neg_index(index)
63
64 def _append(self, value):
65 # Checking value in self will check that value is Hashable
66 if value in self:
67 raise ValueError('Value "%s" already present' % str(value))
68 else:
69 self._dict[value] = len(self)
70 self._list.append(value)
71
72 def _extend(self, values):
73 new_values = set()
74 for value in values:
75 if value in new_values:
76 raise ValueError('New values contain duplicates')
77 elif value in self:
78 raise ValueError('New values contain elements already present in self')
79 else:
80 new_values.add(value)
81 for value in values:
82 self._dict[value] = len(self)
83 self._list.append(value)
84
85 def _add(self, item):
86 if item not in self:
87 self._dict[item] = len(self)
88 self._list.append(item)
89
90 def _update(self, values):
91 for value in values:
92 if value not in self:
93 self._dict[value] = len(self)
94 self._list.append(value)
95
96 @classmethod
97 def _from_iterable(cls, it, **kwargs):
98 return cls(it, **kwargs)
99
100 # Implement Container
101 def __contains__(self, value):
102 return value in self._dict
103
104 # Iterable we get by inheriting from Sequence
105
106 # Implement Sized
107 def __len__(self):
108 return len(self._list)
109
110 # Implement Sequence
111 def __getitem__(self, index):
112 if isinstance(index, slice):
113 return self._from_iterable(self._list[index])
114 return self._list[index]
115
116 def count(self, value):
117 """Return the number of occurrences of value in self.
118
119 This runs in O(1)
120
121 Args:
122 value: The value to count
123 Returns:
124 int: 1 if the value is in the setlist, otherwise 0
125 """
126 if value in self:
127 return 1
128 else:
129 return 0
130
131 def index(self, value, start=0, end=None):
132 """Return the index of value between start and end.
133
134 By default, the entire setlist is searched.
135
136 This runs in O(1)
137
138 Args:
139 value: The value to find the index of
140 start (int): The index to start searching at (defaults to 0)
141 end (int): The index to stop searching at (defaults to the end of the list)
142 Returns:
143 int: The index of the value
144 Raises:
145 ValueError: If the value is not in the list or outside of start - end
146 IndexError: If start or end are out of range
147 """
148 try:
149 index = self._dict[value]
150 except KeyError:
151 raise ValueError
152 else:
153 start = self._fix_neg_index(start)
154 end = self._fix_end_index(end)
155 if start <= index < end:
156 return index
157 else:
158 raise ValueError
159
160 @classmethod
161 def _check_type(cls, other, operand_name):
162 if not isinstance(other, SetList):
163 message = (
164 "unsupported operand type(s) for {operand_name}: "
165 "'{self_type}' and '{other_type}'").format(
166 operand_name=operand_name,
167 self_type=cls,
168 other_type=type(other),
169 )
170 raise TypeError(message)
171
172 def __add__(self, other):
173 self._check_type(other, '+')
174 out = self.copy()
175 out._extend(other)
176 return out
177
178 # Implement Set
179
180 def issubset(self, other):
181 """Report whether another set contains this set."""
182 return self <= other
183
184 def issuperset(self, other):
185 """Report whether this set contains another set."""
186 return self >= other
187
188 def union(self, other):
189 """Return the union of sets as a new set.
190
191 (i.e. all elements that are in either set.)
192 """
193 out = self.copy()
194 out._update(other)
195 return out
196
197 def intersection(self, other):
198 """Return the intersection of two sets as a new set.
199
200 (i.e. all elements that are in both sets.)
201 """
202 other = set(other)
203 return self._from_iterable(item for item in self if item in other)
204
205 def difference(self, other):
206 """Return the difference of two or more sets as a new set.
207
208 (i.e. all elements that are in this set but not the others.)
209 """
210 other = set(other)
211 return self._from_iterable(item for item in self if item not in other)
212
213 def symmetric_difference(self, other):
214 """Return the symmetric difference (disjuntive union) of two sets.
215
216 (i.e. all elements that are in one set but not both.)
217 """
218 return self.union(other) - self.intersection(other)
219
220 def __sub__(self, other):
221 self._check_type(other, '-')
222 return self.difference(other)
223
224 def __and__(self, other):
225 self._check_type(other, '&')
226 return self.intersection(other)
227
228 def __or__(self, other):
229 self._check_type(other, '|')
230 return self.union(other)
231
232 def __xor__(self, other):
233 self._check_type(other, '^')
234 return self.symmetric_difference(other)
235
236 # Comparison
237
238 def __eq__(self, other):
239 if not isinstance(other, SetList):
240 return False
241 if not len(self) == len(other):
242 return False
243 for self_elem, other_elem in zip(self, other):
244 if self_elem != other_elem:
245 return False
246 return True
247
248 def __ne__(self, other):
249 return not (self == other)
250
251 # New methods
252
253 def sub_index(self, sub, start=0, end=None):
254 """Return the index of a subsequence.
255
256 This runs in O(len(sub))
257
258 Args:
259 sub (Sequence): An Iterable to search for
260 start (int): The index at which to start the search
261 end (int): The index at which to end the search
262 Returns:
263 int: The index of the first element of sub
264 Raises:
265 ValueError: If sub isn't a subsequence
266 TypeError: If sub isn't iterable
267 IndexError: If start or end are out of range
268 """
269 start_index = self.index(sub[0], start, end)
270 end = self._fix_end_index(end)
271 if start_index + len(sub) > end:
272 raise ValueError
273 for i in range(1, len(sub)):
274 if sub[i] != self[start_index + i]:
275 raise ValueError
276 return start_index
277
278 def copy(self):
279 """Return a shallow copy of the setlist."""
280 return self.__class__(self)
281
282
283 class setlist(SetList, MutableSequence, MutableSet):
284 """A mutable (unhashable) setlist.
285
286 .. automethod:: __init__
287 """
288
289 def __str__(self):
290 return '{[%s}]' % ', '.join(repr(v) for v in self)
291
292 # Helper methods
293 def _delete_all(self, elems_to_delete, raise_errors):
294 indices_to_delete = set()
295 for elem in elems_to_delete:
296 try:
297 elem_index = self._dict[elem]
298 except KeyError:
299 if raise_errors:
300 raise ValueError('Passed values contain elements not in self')
301 else:
302 if elem_index in indices_to_delete:
303 if raise_errors:
304 raise ValueError('Passed vales contain duplicates')
305 indices_to_delete.add(elem_index)
306 self._delete_values_by_index(indices_to_delete)
307
308 def _delete_values_by_index(self, indices_to_delete):
309 deleted_count = 0
310 for i, elem in enumerate(self._list):
311 if i in indices_to_delete:
312 deleted_count += 1
313 del self._dict[elem]
314 else:
315 new_index = i - deleted_count
316 self._list[new_index] = elem
317 self._dict[elem] = new_index
318 # Now remove deleted_count items from the end of the list
319 if deleted_count:
320 self._list = self._list[:-deleted_count]
321
322 # Set/Sequence agnostic
323 def pop(self, index=-1):
324 """Remove and return the item at index."""
325 value = self._list.pop(index)
326 del self._dict[value]
327 return value
328
329 def clear(self):
330 """Remove all elements from self."""
331 self._dict = dict()
332 self._list = list()
333
334 # Implement MutableSequence
335 def __setitem__(self, index, value):
336 if isinstance(index, slice):
337 old_values = self[index]
338 for v in value:
339 if v in self and v not in old_values:
340 raise ValueError
341 self._list[index] = value
342 self._dict = {}
343 for i, v in enumerate(self._list):
344 self._dict[v] = i
345 else:
346 index = self._fix_neg_index(index)
347 old_value = self._list[index]
348 if value in self:
349 if value == old_value:
350 return
351 else:
352 raise ValueError
353 del self._dict[old_value]
354 self._list[index] = value
355 self._dict[value] = index
356
357 def __delitem__(self, index):
358 if isinstance(index, slice):
359 indices_to_delete = set(self.index(e) for e in self._list[index])
360 self._delete_values_by_index(indices_to_delete)
361 else:
362 index = self._fix_neg_index(index)
363 value = self._list[index]
364 del self._dict[value]
365 for elem in self._list[index + 1:]:
366 self._dict[elem] -= 1
367 del self._list[index]
368
369 def insert(self, index, value):
370 """Insert value at index.
371
372 Args:
373 index (int): Index to insert value at
374 value: Value to insert
375 Raises:
376 ValueError: If value already in self
377 IndexError: If start or end are out of range
378 """
379 if value in self:
380 raise ValueError
381 index = self._fix_neg_index(index)
382 self._dict[value] = index
383 for elem in self._list[index:]:
384 self._dict[elem] += 1
385 self._list.insert(index, value)
386
387 def append(self, value):
388 """Append value to the end.
389
390 Args:
391 value: Value to append
392 Raises:
393 ValueError: If value alread in self
394 TypeError: If value isn't hashable
395 """
396 self._append(value)
397
398 def extend(self, values):
399 """Append all values to the end.
400
401 If any of the values are present, ValueError will
402 be raised and none of the values will be appended.
403
404 Args:
405 values (Iterable): Values to append
406 Raises:
407 ValueError: If any values are already present or there are duplicates
408 in the passed values.
409 TypeError: If any of the values aren't hashable.
410 """
411 self._extend(values)
412
413 def __iadd__(self, values):
414 """Add all values to the end of self.
415
416 Args:
417 values (Iterable): Values to append
418 Raises:
419 ValueError: If any values are already present
420 """
421 self._check_type(values, '+=')
422 self.extend(values)
423 return self
424
425 def remove(self, value):
426 """Remove value from self.
427
428 Args:
429 value: Element to remove from self
430 Raises:
431 ValueError: if element is already present
432 """
433 try:
434 index = self._dict[value]
435 except KeyError:
436 raise ValueError('Value "%s" is not present.')
437 else:
438 del self[index]
439
440 def remove_all(self, elems_to_delete):
441 """Remove all elements from elems_to_delete, raises ValueErrors.
442
443 See Also:
444 discard_all
445 Args:
446 elems_to_delete (Iterable): Elements to remove.
447 Raises:
448 ValueError: If the count of any element is greater in
449 elems_to_delete than self.
450 TypeError: If any of the values aren't hashable.
451 """
452 self._delete_all(elems_to_delete, raise_errors=True)
453
454 def reverse(self):
455 """Reverse the setlist in-place."""
456 self._list.reverse()
457 for index, item in enumerate(self._list):
458 self._dict[item] = index
459
460 # Implement MutableSet
461
462 def add(self, item):
463 """Add an item.
464
465 Note:
466 This does not raise a ValueError for an already present value like
467 append does. This is to match the behavior of set.add
468 Args:
469 item: Item to add
470 Raises:
471 TypeError: If item isn't hashable.
472 """
473 self._add(item)
474
475 def update(self, values):
476 """Add all values to the end.
477
478 If any of the values are present, silently ignore
479 them (as opposed to extend which raises an Error).
480
481 See also:
482 extend
483 Args:
484 values (Iterable): Values to add
485 Raises:
486 TypeError: If any of the values are unhashable.
487 """
488 self._update(values)
489
490 def discard_all(self, elems_to_delete):
491 """Discard all the elements from elems_to_delete.
492
493 This is much faster than removing them one by one.
494 This runs in O(len(self) + len(elems_to_delete))
495
496 Args:
497 elems_to_delete (Iterable): Elements to discard.
498 Raises:
499 TypeError: If any of the values aren't hashable.
500 """
501 self._delete_all(elems_to_delete, raise_errors=False)
502
503 def discard(self, value):
504 """Discard an item.
505
506 Note:
507 This does not raise a ValueError for a missing value like remove does.
508 This matches the behavior of set.discard
509 """
510 try:
511 self.remove(value)
512 except ValueError:
513 pass
514
515 def difference_update(self, other):
516 """Update self to include only the difference with other."""
517 other = set(other)
518 indices_to_delete = set()
519 for i, elem in enumerate(self):
520 if elem in other:
521 indices_to_delete.add(i)
522 if indices_to_delete:
523 self._delete_values_by_index(indices_to_delete)
524
525 def intersection_update(self, other):
526 """Update self to include only the intersection with other."""
527 other = set(other)
528 indices_to_delete = set()
529 for i, elem in enumerate(self):
530 if elem not in other:
531 indices_to_delete.add(i)
532 if indices_to_delete:
533 self._delete_values_by_index(indices_to_delete)
534
535 def symmetric_difference_update(self, other):
536 """Update self to include only the symmetric difference with other."""
537 other = setlist(other)
538 indices_to_delete = set()
539 for i, item in enumerate(self):
540 if item in other:
541 indices_to_delete.add(i)
542 for item in other:
543 self.add(item)
544 self._delete_values_by_index(indices_to_delete)
545
546 def __isub__(self, other):
547 self._check_type(other, '-=')
548 self.difference_update(other)
549 return self
550
551 def __iand__(self, other):
552 self._check_type(other, '&=')
553 self.intersection_update(other)
554 return self
555
556 def __ior__(self, other):
557 self._check_type(other, '|=')
558 self.update(other)
559 return self
560
561 def __ixor__(self, other):
562 self._check_type(other, '^=')
563 self.symmetric_difference_update(other)
564 return self
565
566 # New methods
567 def shuffle(self, random=None):
568 """Shuffle all of the elements in self in place.
569
570 Args:
571 random: A function returning a random float in [0.0, 1.0). If none
572 is passed, the default from `random.shuffle` will be used.
573 """
574 random_.shuffle(self._list, random=random)
575 for i, elem in enumerate(self._list):
576 self._dict[elem] = i
577
578 def sort(self, *args, **kwargs):
579 """Sort this setlist in place."""
580 self._list.sort(*args, **kwargs)
581 for index, value in enumerate(self._list):
582 self._dict[value] = index
583
584 def swap(self, i, j):
585 """Swap the values at indices i & j.
586
587 .. versionadded:: 1.0.3
588 """
589 i = self._fix_neg_index(i)
590 j = self._fix_neg_index(j)
591 self._list[i], self._list[j] = self._list[j], self._list[i]
592 self._dict[self._list[i]] = i
593 self._dict[self._list[j]] = j
594
595
596 class frozensetlist(SetList, Hashable):
597 """An immutable (hashable) setlist.
598
599 .. automethod:: __init__
600 """
601
602 def __hash__(self):
603 if not hasattr(self, '_hash_value'):
604 self._hash_value = _util.hash_iterable(self)
605 return self._hash_value