| 1 |
"""Bag class definitions.""" |
| 2 |
import heapq |
| 3 |
from abc import ABCMeta, abstractmethod |
| 4 |
from collections import defaultdict |
| 5 |
from collections.abc import Collection, Hashable, Set |
| 6 |
from operator import itemgetter |
| 7 |
|
| 8 |
from ._util import deprecated |
| 9 |
|
| 10 |
__all__ = ( |
| 11 |
'Bag', |
| 12 |
'BagView', |
| 13 |
'CountsView', |
| 14 |
'UniqueElementsView', |
| 15 |
'bag', |
| 16 |
'frozenbag', |
| 17 |
) |
| 18 |
|
| 19 |
|
| 20 |
class BagView(Collection): |
| 21 |
"""Base class for bag views.""" |
| 22 |
|
| 23 |
__metaclass__ = ABCMeta |
| 24 |
__slots__ = ('bag', ) |
| 25 |
|
| 26 |
def __init__(self, bag): |
| 27 |
self.bag = bag |
| 28 |
|
| 29 |
def __repr__(self): |
| 30 |
return '{0.__class__.__name__}({0.bag!r})'.format(self) |
| 31 |
|
| 32 |
def __len__(self): |
| 33 |
return self.bag.num_unique_elements() |
| 34 |
|
| 35 |
@abstractmethod |
| 36 |
def __iter__(self): |
| 37 |
raise NotImplementedError |
| 38 |
|
| 39 |
@abstractmethod |
| 40 |
def __contains__(self, elem): |
| 41 |
raise NotImplementedError |
| 42 |
|
| 43 |
|
| 44 |
class UniqueElementsView(BagView): |
| 45 |
"""A view for the unique items and their counts in a bag. |
| 46 |
|
| 47 |
.. versionadded:: 1.0 |
| 48 |
""" |
| 49 |
|
| 50 |
def __iter__(self): |
| 51 |
for elem in self.bag._dict: |
| 52 |
yield elem |
| 53 |
|
| 54 |
def __contains__(self, elem): |
| 55 |
return elem in self.bag |
| 56 |
|
| 57 |
|
| 58 |
class CountsView(BagView): |
| 59 |
"""A view for the unique items and their counts in a bag. |
| 60 |
|
| 61 |
.. versionadded:: 1.0 |
| 62 |
""" |
| 63 |
|
| 64 |
__slots__ = ('bag', ) |
| 65 |
|
| 66 |
def __len__(self): |
| 67 |
return self.bag.num_unique_elements() |
| 68 |
|
| 69 |
def __iter__(self): |
| 70 |
for elem in self.bag.unique_elements(): |
| 71 |
yield elem, self.bag.count(elem) |
| 72 |
|
| 73 |
def __contains__(self, item): |
| 74 |
elem, count = item |
| 75 |
return self.bag.count(elem) == count |
| 76 |
|
| 77 |
|
| 78 |
class Bag(Collection): |
| 79 |
"""Base class for bag classes. |
| 80 |
|
| 81 |
Base class for bag and frozenbag. Is not mutable and not hashable, so there's |
| 82 |
no reason to use this instead of either bag or frozenbag. |
| 83 |
""" |
| 84 |
|
| 85 |
# Basic object methods |
| 86 |
|
| 87 |
def __init__(self, iterable=None): |
| 88 |
"""Create a new bag. |
| 89 |
|
| 90 |
If iterable isn't given, is None or is empty then the bag starts empty. |
| 91 |
Otherwise each element from iterable will be added to the bag |
| 92 |
however many times it appears. |
| 93 |
|
| 94 |
This runs in O(len(iterable)) |
| 95 |
""" |
| 96 |
self._dict = dict() |
| 97 |
self._size = 0 |
| 98 |
if iterable: |
| 99 |
if isinstance(iterable, Bag): |
| 100 |
self._dict = iterable._dict.copy() |
| 101 |
self._size = iterable._size |
| 102 |
else: |
| 103 |
for value in iterable: |
| 104 |
self._increment_count(value) |
| 105 |
|
| 106 |
def _set_count(self, elem, count): |
| 107 |
if count < 0: |
| 108 |
raise ValueError |
| 109 |
self._size += count - self.count(elem) |
| 110 |
if count == 0: |
| 111 |
self._dict.pop(elem, None) |
| 112 |
else: |
| 113 |
self._dict[elem] = count |
| 114 |
|
| 115 |
def _increment_count(self, elem, count=1): |
| 116 |
self._set_count(elem, self.count(elem) + count) |
| 117 |
|
| 118 |
@classmethod |
| 119 |
def _from_iterable(cls, it): |
| 120 |
return cls(it) |
| 121 |
|
| 122 |
def copy(self): |
| 123 |
"""Create a shallow copy of self. |
| 124 |
|
| 125 |
This runs in O(len(self.num_unique_elements())) |
| 126 |
""" |
| 127 |
out = self._from_iterable(None) |
| 128 |
out._dict = self._dict.copy() |
| 129 |
out._size = self._size |
| 130 |
return out |
| 131 |
|
| 132 |
def __repr__(self): |
| 133 |
if self._size == 0: |
| 134 |
return '{0}()'.format(self.__class__.__name__) |
| 135 |
else: |
| 136 |
repr_format = '{class_name}({values!r})' |
| 137 |
return repr_format.format( |
| 138 |
class_name=self.__class__.__name__, |
| 139 |
values=tuple(self), |
| 140 |
) |
| 141 |
|
| 142 |
def __str__(self): |
| 143 |
if self._size == 0: |
| 144 |
return '{class_name}()'.format(class_name=self.__class__.__name__) |
| 145 |
else: |
| 146 |
format_single = '{elem!r}' |
| 147 |
format_mult = '{elem!r}^{mult}' |
| 148 |
strings = [] |
| 149 |
for elem, mult in self.counts(): |
| 150 |
if mult > 1: |
| 151 |
strings.append(format_mult.format(elem=elem, mult=mult)) |
| 152 |
else: |
| 153 |
strings.append(format_single.format(elem=elem)) |
| 154 |
return '{%s}' % ', '.join(strings) |
| 155 |
|
| 156 |
# New public methods (not overriding/implementing anything) |
| 157 |
|
| 158 |
def num_unique_elements(self): |
| 159 |
"""Return the number of unique elements. |
| 160 |
|
| 161 |
This runs in O(1) time |
| 162 |
""" |
| 163 |
return len(self._dict) |
| 164 |
|
| 165 |
def unique_elements(self): |
| 166 |
"""Return a view of unique elements in this bag.""" |
| 167 |
return UniqueElementsView(self) |
| 168 |
|
| 169 |
def count(self, value): |
| 170 |
"""Return the number of value present in this bag. |
| 171 |
|
| 172 |
If value is not in the bag no Error is raised, instead 0 is returned. |
| 173 |
|
| 174 |
This runs in O(1) time |
| 175 |
|
| 176 |
Args: |
| 177 |
value: The element of self to get the count of |
| 178 |
Returns: |
| 179 |
int: The count of value in self |
| 180 |
""" |
| 181 |
return self._dict.get(value, 0) |
| 182 |
|
| 183 |
@deprecated( |
| 184 |
"Use `heapq.nlargest(n, self.counts(), key=itemgetter(1))` instead or " |
| 185 |
"`sorted(self.counts(), reverse=True, key=itemgetter(1))` for `n=None`", |
| 186 |
'1.0', |
| 187 |
) |
| 188 |
def nlargest(self, n=None): |
| 189 |
"""List the n most common elements and their counts. |
| 190 |
|
| 191 |
List is from the most |
| 192 |
common to the least. If n is None, the list all element counts. |
| 193 |
|
| 194 |
Run time should be O(m log m) where m is len(self) |
| 195 |
Args: |
| 196 |
n (int): The number of elements to return |
| 197 |
""" |
| 198 |
if n is None: |
| 199 |
return sorted(self.counts(), key=itemgetter(1), reverse=True) |
| 200 |
else: |
| 201 |
return heapq.nlargest(n, self.counts(), key=itemgetter(1)) |
| 202 |
|
| 203 |
def counts(self): |
| 204 |
"""Return a view of the unique elements in self and their counts. |
| 205 |
|
| 206 |
.. versionadded:: 1.0.3 |
| 207 |
""" |
| 208 |
return CountsView(self) |
| 209 |
|
| 210 |
@classmethod |
| 211 |
def from_mapping(cls, mapping): |
| 212 |
"""Create a bag from a dict of elem->count. |
| 213 |
|
| 214 |
Each key in the dict is added if the value is > 0. |
| 215 |
|
| 216 |
Raises: |
| 217 |
ValueError: If any count is < 0. |
| 218 |
""" |
| 219 |
out = cls() |
| 220 |
for elem, count in mapping.items(): |
| 221 |
out._set_count(elem, count) |
| 222 |
return out |
| 223 |
|
| 224 |
# implementing Sized methods |
| 225 |
|
| 226 |
def __len__(self): |
| 227 |
"""Return the cardinality of the bag. |
| 228 |
|
| 229 |
This runs in O(1) |
| 230 |
""" |
| 231 |
return self._size |
| 232 |
|
| 233 |
# implementing Container methods |
| 234 |
|
| 235 |
def __contains__(self, value): |
| 236 |
"""Return the multiplicity of the element. |
| 237 |
|
| 238 |
This runs in O(1) |
| 239 |
""" |
| 240 |
return self.count(value) |
| 241 |
|
| 242 |
# implementing Iterable methods |
| 243 |
|
| 244 |
def __iter__(self): |
| 245 |
"""Iterate through all elements. |
| 246 |
|
| 247 |
Multiple copies will be returned if they exist. |
| 248 |
""" |
| 249 |
for value, count in self.counts(): |
| 250 |
for _ in range(count): |
| 251 |
yield value |
| 252 |
|
| 253 |
# Comparison methods |
| 254 |
|
| 255 |
def issubset(self, other): |
| 256 |
"""Check that every element in self has a count <= in other. |
| 257 |
|
| 258 |
Args: |
| 259 |
other (Iterable) |
| 260 |
""" |
| 261 |
if not isinstance(other, Bag): |
| 262 |
return self.issubset(frozenbag(other)) |
| 263 |
for elem, count in self.counts(): |
| 264 |
if not count <= other.count(elem): |
| 265 |
return False |
| 266 |
return True |
| 267 |
|
| 268 |
def issuperset(self, other): |
| 269 |
"""Check that every element in self has a count >= in other. |
| 270 |
|
| 271 |
Args: |
| 272 |
other (Iterable) |
| 273 |
""" |
| 274 |
if not isinstance(other, Bag): |
| 275 |
return self.issuperset(bag(other)) |
| 276 |
for elem, count in other.counts(): |
| 277 |
if not self.count(elem) >= count: |
| 278 |
return False |
| 279 |
return True |
| 280 |
|
| 281 |
def __le__(self, other): |
| 282 |
if not isinstance(other, Bag): |
| 283 |
return NotImplemented |
| 284 |
return len(self) <= len(other) and self.issubset(other) |
| 285 |
|
| 286 |
def __lt__(self, other): |
| 287 |
if not isinstance(other, Bag): |
| 288 |
return NotImplemented |
| 289 |
return len(self) < len(other) and self.issubset(other) |
| 290 |
|
| 291 |
def __gt__(self, other): |
| 292 |
if not isinstance(other, Bag): |
| 293 |
return NotImplemented |
| 294 |
return len(self) > len(other) and self.issuperset(other) |
| 295 |
|
| 296 |
def __ge__(self, other): |
| 297 |
if not isinstance(other, Bag): |
| 298 |
return NotImplemented |
| 299 |
return len(self) >= len(other) and self.issuperset(other) |
| 300 |
|
| 301 |
def __eq__(self, other): |
| 302 |
if not isinstance(other, Bag): |
| 303 |
return False |
| 304 |
return self._dict == other._dict |
| 305 |
|
| 306 |
def __ne__(self, other): |
| 307 |
return not (self == other) |
| 308 |
|
| 309 |
# Operations - &, |, +, -, ^, * and isdisjoint |
| 310 |
|
| 311 |
def _iadd(self, other): |
| 312 |
"""Add all of the elements of other to self. |
| 313 |
|
| 314 |
if isinstance(it, Bag): |
| 315 |
This runs in O(it.num_unique_elements()) |
| 316 |
else: |
| 317 |
This runs in O(len(it)) |
| 318 |
""" |
| 319 |
if isinstance(other, Bag): |
| 320 |
for elem, count in other.counts(): |
| 321 |
self._increment_count(elem, count) |
| 322 |
else: |
| 323 |
for elem in other: |
| 324 |
self._increment_count(elem, 1) |
| 325 |
return self |
| 326 |
|
| 327 |
def _iand(self, other): |
| 328 |
"""Set multiplicity of each element to the minimum of the two collections. |
| 329 |
|
| 330 |
if isinstance(other, Bag): |
| 331 |
This runs in O(other.num_unique_elements()) |
| 332 |
else: |
| 333 |
This runs in O(len(other)) |
| 334 |
""" |
| 335 |
# TODO do we have to create a bag from the other first? |
| 336 |
if not isinstance(other, Bag): |
| 337 |
other = self._from_iterable(other) |
| 338 |
for elem, old_count in set(self.counts()): |
| 339 |
other_count = other.count(elem) |
| 340 |
new_count = min(other_count, old_count) |
| 341 |
self._set_count(elem, new_count) |
| 342 |
return self |
| 343 |
|
| 344 |
def _ior(self, other): |
| 345 |
"""Set multiplicity of each element to the maximum of the two collections. |
| 346 |
|
| 347 |
if isinstance(other, Bag): |
| 348 |
This runs in O(other.num_unique_elements()) |
| 349 |
else: |
| 350 |
This runs in O(len(other)) |
| 351 |
""" |
| 352 |
# TODO do we have to create a bag from the other first? |
| 353 |
if not isinstance(other, Bag): |
| 354 |
other = self._from_iterable(other) |
| 355 |
for elem, other_count in other.counts(): |
| 356 |
old_count = self.count(elem) |
| 357 |
new_count = max(other_count, old_count) |
| 358 |
self._set_count(elem, new_count) |
| 359 |
return self |
| 360 |
|
| 361 |
def _ixor(self, other): |
| 362 |
"""Set self to the symmetric difference between the sets. |
| 363 |
|
| 364 |
if isinstance(other, Bag): |
| 365 |
This runs in O(other.num_unique_elements()) |
| 366 |
else: |
| 367 |
This runs in O(len(other)) |
| 368 |
""" |
| 369 |
if isinstance(other, Bag): |
| 370 |
for elem, other_count in other.counts(): |
| 371 |
count = abs(self.count(elem) - other_count) |
| 372 |
self._set_count(elem, count) |
| 373 |
else: |
| 374 |
# Let a = self.count(elem) and b = other.count(elem) |
| 375 |
# if a >= b then elem is removed from self b times leaving a - b |
| 376 |
# if a < b then elem is removed from self a times then added (b - a) |
| 377 |
# times leaving a - a + (b - a) = b - a |
| 378 |
for elem in other: |
| 379 |
try: |
| 380 |
self._increment_count(elem, -1) |
| 381 |
except ValueError: |
| 382 |
self._increment_count(elem, 1) |
| 383 |
return self |
| 384 |
|
| 385 |
def _isub(self, other): |
| 386 |
"""Discard the elements of other from self. |
| 387 |
|
| 388 |
if isinstance(it, Bag): |
| 389 |
This runs in O(it.num_unique_elements()) |
| 390 |
else: |
| 391 |
This runs in O(len(it)) |
| 392 |
""" |
| 393 |
if isinstance(other, Bag): |
| 394 |
for elem, other_count in other.counts(): |
| 395 |
try: |
| 396 |
self._increment_count(elem, -other_count) |
| 397 |
except ValueError: |
| 398 |
self._set_count(elem, 0) |
| 399 |
else: |
| 400 |
for elem in other: |
| 401 |
try: |
| 402 |
self._increment_count(elem, -1) |
| 403 |
except ValueError: |
| 404 |
pass |
| 405 |
return self |
| 406 |
|
| 407 |
def __and__(self, other): |
| 408 |
"""Intersection is the minimum of corresponding counts. |
| 409 |
|
| 410 |
This runs in O(l + n) where: |
| 411 |
* n is self.num_unique_elements() |
| 412 |
* `l = 1` if other is a bag else `l = len(other)` |
| 413 |
|
| 414 |
""" |
| 415 |
return self.copy()._iand(other) |
| 416 |
|
| 417 |
def isdisjoint(self, other): |
| 418 |
"""Return if this bag is disjoint with the passed collection. |
| 419 |
|
| 420 |
This runs in O(len(other)) |
| 421 |
""" |
| 422 |
for value in other: |
| 423 |
if value in self: |
| 424 |
return False |
| 425 |
return True |
| 426 |
|
| 427 |
def __or__(self, other): |
| 428 |
"""Union is the maximum of all elements. |
| 429 |
|
| 430 |
This runs in O(m + n) where: |
| 431 |
* `n = self.num_unique_elements()` |
| 432 |
* m = other.num_unique_elements() if other is a bag else m = len(other) |
| 433 |
""" |
| 434 |
return self.copy()._ior(other) |
| 435 |
|
| 436 |
def __add__(self, other): |
| 437 |
"""Return a new bag also containing all the elements of other. |
| 438 |
|
| 439 |
self + other = self & other + self | other |
| 440 |
|
| 441 |
This runs in O(m + n) where: |
| 442 |
* n is self.num_unique_elements() |
| 443 |
* m is len(other) |
| 444 |
|
| 445 |
Args: |
| 446 |
other (Iterable): elements to add to self |
| 447 |
|
| 448 |
""" |
| 449 |
return self.copy()._iadd(other) |
| 450 |
|
| 451 |
def __sub__(self, other): |
| 452 |
"""Difference between the sets. |
| 453 |
|
| 454 |
For normal sets this is all x s.t. x in self and x not in other. |
| 455 |
For bags this is count(x) = max(0, self.count(x)-other.count(x)) |
| 456 |
|
| 457 |
This runs in O(m + n) where: |
| 458 |
* n is self.num_unique_elements() |
| 459 |
* m is len(other) |
| 460 |
|
| 461 |
Args: |
| 462 |
other (Iterable): elements to remove |
| 463 |
|
| 464 |
""" |
| 465 |
return self.copy()._isub(other) |
| 466 |
|
| 467 |
def __mul__(self, other): |
| 468 |
"""Cartesian product with other.""" |
| 469 |
return self.product(other) |
| 470 |
|
| 471 |
def product(self, other, operator=None): |
| 472 |
"""Cartesian product of the two sets. |
| 473 |
|
| 474 |
Optionally, pass an operator to combine elements instead of creating a |
| 475 |
tuple. |
| 476 |
|
| 477 |
This should run in O(m*n+l) where: |
| 478 |
* `m` is the number of unique elements in `self` |
| 479 |
* `n` is the number of unique elements in `other` |
| 480 |
* `l` is 0 if `other` is a bag, else `l` is the `len(other)` |
| 481 |
|
| 482 |
Args: |
| 483 |
other (Iterable): The iterable to take the product with. |
| 484 |
operator (Callable): A function that accepts an element from self |
| 485 |
and other and returns a combined value to include in the return |
| 486 |
value. |
| 487 |
""" |
| 488 |
if not isinstance(other, Bag): |
| 489 |
other = self._from_iterable(other) |
| 490 |
values = defaultdict(int) |
| 491 |
for elem, count in self.counts(): |
| 492 |
for other_elem, other_count in other.counts(): |
| 493 |
if operator: |
| 494 |
new_elem = operator(elem, other_elem) |
| 495 |
else: |
| 496 |
new_elem = (elem, other_elem) |
| 497 |
new_count = count * other_count |
| 498 |
values[new_elem] += new_count |
| 499 |
return self.from_mapping(values) |
| 500 |
|
| 501 |
def __xor__(self, other): |
| 502 |
"""Symmetric difference between the sets. |
| 503 |
|
| 504 |
other can be any iterable. |
| 505 |
|
| 506 |
This runs in O(m + n) where: |
| 507 |
m = len(self) |
| 508 |
n = len(other) |
| 509 |
""" |
| 510 |
return self.copy()._ixor(other) |
| 511 |
|
| 512 |
|
| 513 |
class bag(Bag): |
| 514 |
"""bag is a mutable unhashable bag. |
| 515 |
|
| 516 |
.. automethod:: __init__ |
| 517 |
""" |
| 518 |
|
| 519 |
def pop(self): |
| 520 |
"""Remove and return an element of self.""" |
| 521 |
# TODO can this be done more efficiently (no need to create an iterator)? |
| 522 |
it = iter(self) |
| 523 |
try: |
| 524 |
value = next(it) |
| 525 |
except StopIteration: |
| 526 |
raise KeyError('pop from an empty bag') |
| 527 |
self.remove(value) |
| 528 |
return value |
| 529 |
|
| 530 |
def add(self, elem): |
| 531 |
"""Add elem to self.""" |
| 532 |
self._increment_count(elem) |
| 533 |
|
| 534 |
def discard(self, elem): |
| 535 |
"""Remove elem from this bag, silent if it isn't present.""" |
| 536 |
try: |
| 537 |
self.remove(elem) |
| 538 |
except ValueError: |
| 539 |
pass |
| 540 |
|
| 541 |
def remove(self, elem): |
| 542 |
"""Remove elem from this bag, raising a ValueError if it isn't present. |
| 543 |
|
| 544 |
Args: |
| 545 |
elem: object to remove from self |
| 546 |
Raises: |
| 547 |
ValueError: if the elem isn't present |
| 548 |
""" |
| 549 |
self._increment_count(elem, -1) |
| 550 |
|
| 551 |
def discard_all(self, other): |
| 552 |
"""Discard all of the elems from other.""" |
| 553 |
self._isub(other) |
| 554 |
|
| 555 |
def remove_all(self, other): |
| 556 |
"""Remove all of the elems from other. |
| 557 |
|
| 558 |
Raises a ValueError if the multiplicity of any elem in other is greater |
| 559 |
than in self. |
| 560 |
""" |
| 561 |
if not self.issuperset(other): |
| 562 |
raise ValueError('Passed collection is not a subset of this bag') |
| 563 |
self.discard_all(other) |
| 564 |
|
| 565 |
def clear(self): |
| 566 |
"""Remove all elements from this bag.""" |
| 567 |
self._dict = dict() |
| 568 |
self._size = 0 |
| 569 |
|
| 570 |
# In-place operations |
| 571 |
|
| 572 |
__ior__ = Bag._ior |
| 573 |
__iand__ = Bag._iand |
| 574 |
__ixor__ = Bag._ixor |
| 575 |
__isub__ = Bag._isub |
| 576 |
__iadd__ = Bag._iadd |
| 577 |
|
| 578 |
|
| 579 |
class frozenbag(Bag, Hashable): |
| 580 |
"""frozenbag is an immutable, hashable bag. |
| 581 |
|
| 582 |
.. automethod:: __init__ |
| 583 |
""" |
| 584 |
|
| 585 |
def __hash__(self): |
| 586 |
"""Compute the hash value of a frozenbag.""" |
| 587 |
if not hasattr(self, '_hash_value'): |
| 588 |
self._hash_value = Set._hash(self) |
| 589 |
return self._hash_value |