forked from wheerd/multiset
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmultiset.py
More file actions
1088 lines (871 loc) · 37.9 KB
/
multiset.py
File metadata and controls
1088 lines (871 loc) · 37.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""An implementation of a multiset."""
import sys
from collections import defaultdict
from collections.abc import Iterable, Mapping, MutableMapping, Set, Sized, Container
from itertools import chain, repeat, starmap
_sequence_types = (tuple, list, range, set, frozenset, str)
_iter_types = (type(iter([])), type((lambda: (yield))()))
_all_basic_types = _sequence_types + _iter_types + (dict, )
__all__ = ['BaseMultiset', 'Multiset', 'FrozenMultiset']
class BaseMultiset(object):
"""A multiset implementation.
A multiset is similar to the builtin :class:`set`, but elements can occur multiple times in the multiset.
It is also similar to a :class:`list` without ordering of the values and hence no index-based operations.
The multiset internally uses a :class:`dict` for storage where the key is the element and the value its
multiplicity. It supports all operations that the :class:`set` supports.
In contrast to the builtin :class:`collections.Counter`, no negative counts are allowed, elements with
zero counts are removed from the :class:`dict`, and set operations are supported.
The multiset comes in two variants, `Multiset` and `FrozenMultiset` which correspond to the `set` and
`frozenset` classes, respectively.
.. warning::
You cannot instantiate this class directly. Use one of its variants instead.
:see: https://en.wikipedia.org/wiki/Multiset
"""
__slots__ = ('_elements', '_total')
def __init__(self, iterable=None):
r"""Create a new, empty Multiset object.
And if given, initialize with elements from input iterable.
Or, initialize from a mapping of elements to their multiplicity.
Example:
>>> ms = Multiset() # a new, empty multiset
>>> ms = Multiset('abc') # a new multiset from an iterable
>>> ms = Multiset({'a': 4, 'b': 2}) # a new multiset from a mapping
Args:
iterable:
An optional iterable of elements or mapping of elements to multiplicity to
initialize the multiset from.
"""
if isinstance(iterable, BaseMultiset):
self._elements = iterable._elements.copy()
self._total = iterable._total
else:
self._elements = _elements = defaultdict(int)
_total = 0
if iterable is not None:
if isinstance(iterable, _sequence_types):
for element in iterable:
_elements[element] += 1
_total = len(iterable)
elif isinstance(iterable, dict):
for element, multiplicity in iterable.items():
if multiplicity > 0:
_elements[element] = multiplicity
_total += multiplicity
elif isinstance(iterable, _iter_types):
for element in iterable:
_elements[element] += 1
_total += 1
elif isinstance(iterable, Mapping):
for element, multiplicity in iterable.items():
if multiplicity > 0:
_elements[element] = multiplicity
_total += multiplicity
elif isinstance(iterable, Sized):
for element in iterable:
_elements[element] += 1
_total = len(iterable)
else:
for element in iterable:
_elements[element] += 1
_total += 1
self._total = _total
def __new__(cls, iterable=None):
if cls is BaseMultiset:
raise TypeError("Cannot instantiate BaseMultiset directly, use either Multiset or FrozenMultiset.")
return super(BaseMultiset, cls).__new__(cls)
def __contains__(self, element):
return element in self._elements
def __getitem__(self, element):
"""The multiplicity of an element or zero if it is not in the multiset."""
return self._elements.get(element, 0)
def __str__(self):
return '{%s}' % ', '.join(map(str, self.__iter__()))
def __repr__(self):
items = ', '.join('%r: %r' % item for item in self._elements.items())
return '%s({%s})' % (self.__class__.__name__, items)
def __len__(self):
"""Returns the total number of elements in the multiset.
Note that this is equivalent to the sum of the multiplicities:
>>> ms = Multiset('aab')
>>> len(ms)
3
>>> sum(ms.multiplicities())
3
If you need the total number of distinct elements, use either the :meth:`distinct_elements` method:
>>> len(ms.distinct_elements())
2
or convert to a :class:`set`:
>>> len(set(ms))
2
"""
return self._total
def __bool__(self):
return self._total > 0
def __iter__(self):
return chain.from_iterable(starmap(repeat, self._elements.items()))
def isdisjoint(self, other):
r"""Return True if the set has no elements in common with other.
Sets are disjoint iff their intersection is the empty set.
>>> ms = Multiset('aab')
>>> ms.isdisjoint('bc')
False
>>> ms.isdisjoint(Multiset('ccd'))
True
Args:
other: The other set to check disjointedness. Can also be an :class:`~typing.Iterable`\[~T]
or :class:`~typing.Mapping`\[~T, :class:`int`] which are then converted to :class:`Multiset`\[~T].
"""
if isinstance(other, _sequence_types + (BaseMultiset, )):
pass
elif not isinstance(other, Container):
other = self._as_multiset(other)
return all(element not in other for element in self._elements.keys())
def difference(self, *others):
r"""Return a new multiset with all elements from the others removed.
>>> ms = Multiset('aab')
>>> sorted(ms.difference('bc'))
['a', 'a']
You can also use the ``-`` operator for the same effect. However, the operator version
will only accept a set as other operator, not any iterable, to avoid errors.
>>> ms = Multiset('aabbbc')
>>> sorted(ms - Multiset('abd'))
['a', 'b', 'b', 'c']
For a variant of the operation which modifies the multiset in place see
:meth:`difference_update`.
Args:
others: The other sets to remove from the multiset. Can also be any :class:`~typing.Iterable`\[~T]
or :class:`~typing.Mapping`\[~T, :class:`int`] which are then converted to :class:`Multiset`\[~T].
Returns:
The resulting difference multiset.
"""
result = self.__copy__()
_elements = result._elements
_total = result._total
for other in map(self._as_multiset, others):
for element, multiplicity in other.items():
if element in _elements:
old_multiplicity = _elements[element]
new_multiplicity = old_multiplicity - multiplicity
if new_multiplicity > 0:
_elements[element] = new_multiplicity
_total -= multiplicity
else:
del _elements[element]
_total -= old_multiplicity
result._total = _total
return result
def __sub__(self, other):
if isinstance(other, (BaseMultiset, set, frozenset)):
pass
elif not isinstance(other, Set):
return NotImplemented
return self.difference(other)
def __rsub__(self, other):
if not isinstance(other, (Set, BaseMultiset)):
return NotImplemented
return self._as_multiset(other).difference(self)
def union(self, *others):
r"""Return a new multiset with all elements from the multiset and the others with maximal multiplicities.
>>> ms = Multiset('aab')
>>> sorted(ms.union('bc'))
['a', 'a', 'b', 'c']
You can also use the ``|`` operator for the same effect. However, the operator version
will only accept a set as other operator, not any iterable, to avoid errors.
>>> ms = Multiset('aab')
>>> sorted(ms | Multiset('aaa'))
['a', 'a', 'a', 'b']
For a variant of the operation which modifies the multiset in place see
:meth:`union_update`.
Args:
*others: The other sets to union the multiset with. Can also be any :class:`~typing.Iterable`\[~T]
or :class:`~typing.Mapping`\[~T, :class:`int`] which are then converted to :class:`Multiset`\[~T].
Returns:
The multiset resulting from the union.
"""
result = self.__copy__()
_elements = result._elements
_total = result._total
for other in map(self._as_mapping, others):
for element, multiplicity in other.items():
old_multiplicity = _elements.get(element, 0)
if multiplicity > old_multiplicity:
_elements[element] = multiplicity
_total += multiplicity - old_multiplicity
result._total = _total
return result
def __or__(self, other):
if isinstance(other, (BaseMultiset, set, frozenset)):
pass
elif not isinstance(other, Set):
return NotImplemented
return self.union(other)
__ror__ = __or__
def combine(self, *others):
r"""Return a new multiset with all elements from the multiset and the others with their multiplicities summed up.
>>> ms = Multiset('aab')
>>> sorted(ms.combine('bc'))
['a', 'a', 'b', 'b', 'c']
You can also use the ``+`` operator for the same effect. However, the operator version
will only accept a set as other operator, not any iterable, to avoid errors.
>>> ms = Multiset('aab')
>>> sorted(ms + Multiset('a'))
['a', 'a', 'a', 'b']
For a variant of the operation which modifies the multiset in place see
:meth:`update`.
Args:
others: The other sets to add to the multiset. Can also be any :class:`~typing.Iterable`\[~T]
or :class:`~typing.Mapping`\[~T, :class:`int`] which are then converted to :class:`Multiset`\[~T].
Returns:
The multiset resulting from the addition of the sets.
"""
result = self.__copy__()
_elements = result._elements
_total = result._total
for other in map(self._as_mapping, others):
for element, multiplicity in other.items():
old_multiplicity = _elements.get(element, 0)
new_multiplicity = old_multiplicity + multiplicity
if old_multiplicity > 0 and new_multiplicity <= 0:
del _elements[element]
_total -= old_multiplicity
elif new_multiplicity > 0:
_elements[element] = new_multiplicity
_total += multiplicity
result._total = _total
return result
def __add__(self, other):
if isinstance(other, (BaseMultiset, set, frozenset)):
pass
elif not isinstance(other, Set):
return NotImplemented
return self.combine(other)
__radd__ = __add__
def intersection(self, *others):
r"""Return a new multiset with elements common to the multiset and all others.
>>> ms = Multiset('aab')
>>> sorted(ms.intersection('abc'))
['a', 'b']
You can also use the ``&`` operator for the same effect. However, the operator version
will only accept a set as other operator, not any iterable, to avoid errors.
>>> ms = Multiset('aab')
>>> sorted(ms & Multiset('aaac'))
['a', 'a']
For a variant of the operation which modifies the multiset in place see
:meth:`intersection_update`.
Args:
others: The other sets intersect with the multiset. Can also be any :class:`~typing.Iterable`\[~T]
or :class:`~typing.Mapping`\[~T, :class:`int`] which are then converted to :class:`Multiset`\[~T].
Returns:
The multiset resulting from the intersection of the sets.
"""
result = self.__copy__()
_elements = result._elements
_total = result._total
for other in map(self._as_mapping, others):
for element, multiplicity in list(_elements.items()):
new_multiplicity = other.get(element, 0)
if new_multiplicity < multiplicity:
if new_multiplicity > 0:
_elements[element] = new_multiplicity
_total -= multiplicity - new_multiplicity
else:
del _elements[element]
_total -= multiplicity
result._total = _total
return result
def __and__(self, other):
if isinstance(other, (BaseMultiset, set, frozenset)):
pass
elif not isinstance(other, Set):
return NotImplemented
return self.intersection(other)
__rand__ = __and__
def symmetric_difference(self, other):
r"""Return a new set with elements in either the set or other but not both.
>>> ms = Multiset('aab')
>>> sorted(ms.symmetric_difference('abc'))
['a', 'c']
You can also use the ``^`` operator for the same effect. However, the operator version
will only accept a set as other operator, not any iterable, to avoid errors.
>>> ms = Multiset('aab')
>>> sorted(ms ^ Multiset('aaac'))
['a', 'b', 'c']
For a variant of the operation which modifies the multiset in place see
:meth:`symmetric_difference_update`.
Args:
other: The other set to take the symmetric difference with. Can also be any :class:`~typing.Iterable`\[~T]
or :class:`~typing.Mapping`\[~T, :class:`int`] which are then converted to :class:`Multiset`\[~T].
Returns:
The resulting symmetric difference multiset.
"""
other = self._as_multiset(other)
result = self.__class__()
_total = 0
_elements = result._elements
self_elements = self._elements
other_elements = other._elements
dist_elements = set(self_elements.keys()) | set(other_elements.keys())
for element in dist_elements:
multiplicity = self_elements.get(element, 0)
other_multiplicity = other_elements.get(element, 0)
new_multiplicity = (multiplicity - other_multiplicity
if multiplicity > other_multiplicity else other_multiplicity - multiplicity)
_total += new_multiplicity
if new_multiplicity > 0:
_elements[element] = new_multiplicity
result._total = _total
return result
def __xor__(self, other):
if isinstance(other, (BaseMultiset, set, frozenset)):
pass
elif not isinstance(other, Set):
return NotImplemented
return self.symmetric_difference(other)
__rxor__ = __xor__
def times(self, factor):
"""Return a new set with each element's multiplicity multiplied with the given scalar factor.
>>> ms = Multiset('aab')
>>> sorted(ms.times(2))
['a', 'a', 'a', 'a', 'b', 'b']
You can also use the ``*`` operator for the same effect:
>>> sorted(ms * 3)
['a', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'b']
For a variant of the operation which modifies the multiset in place see
:meth:`times_update`.
Args:
factor: The factor to multiply each multiplicity with.
"""
if factor == 0:
return self.__class__()
if factor < 0:
raise ValueError('The factor must no be negative.')
result = self.__copy__()
_elements = result._elements
for element in _elements:
_elements[element] *= factor
result._total *= factor
return result
def __mul__(self, factor):
if not isinstance(factor, int):
return NotImplemented
return self.times(factor)
__rmul__ = __mul__
def _issubset(self, other, strict):
other = self._as_multiset(other)
self_len = self._total
other_len = len(other)
if self_len > other_len:
return False
if self_len == other_len and strict:
return False
return all(multiplicity <= other[element] for element, multiplicity in self.items())
def issubset(self, other):
"""Return True iff this set is a subset of the other.
>>> Multiset('ab').issubset('aabc')
True
>>> Multiset('aabb').issubset(Multiset('aabc'))
False
You can also use the ``<=`` operator for this comparison:
>>> Multiset('ab') <= Multiset('ab')
True
When using the ``<`` operator for comparison, the sets are checked
to be unequal in addition:
>>> Multiset('ab') < Multiset('ab')
False
Args:
other: The potential superset of the multiset to be checked.
Returns:
True iff this set is a subset of the other.
"""
return self._issubset(other, False)
def __le__(self, other):
if isinstance(other, (BaseMultiset, set, frozenset)):
pass
elif not isinstance(other, Set):
return NotImplemented
return self._issubset(other, False)
def __lt__(self, other):
if isinstance(other, (BaseMultiset, set, frozenset)):
pass
elif not isinstance(other, Set):
return NotImplemented
return self._issubset(other, True)
def _issuperset(self, other, strict):
other = self._as_multiset(other)
other_len = len(other)
if len(self) < other_len:
return False
if len(self) == other_len and strict:
return False
for element, multiplicity in other.items():
if self[element] < multiplicity:
return False
return True
def issuperset(self, other):
"""Return True iff this multiset is a superset of the other.
>>> Multiset('aabc').issuperset('ab')
True
>>> Multiset('aabc').issuperset(Multiset('abcc'))
False
You can also use the ``>=`` operator for this comparison:
>>> Multiset('ab') >= Multiset('ab')
True
When using the ``>`` operator for comparison, the sets are checked
to be unequal in addition:
>>> Multiset('ab') > Multiset('ab')
False
Args:
other: The potential subset of the multiset to be checked.
Returns:
True iff this set is a subset of the other.
"""
return self._issuperset(other, False)
def __ge__(self, other):
if isinstance(other, (BaseMultiset, set, frozenset)):
pass
elif not isinstance(other, Set):
return NotImplemented
return self._issuperset(other, False)
def __gt__(self, other):
if isinstance(other, (BaseMultiset, set, frozenset)):
pass
elif not isinstance(other, Set):
return NotImplemented
return self._issuperset(other, True)
def __eq__(self, other):
if isinstance(other, BaseMultiset):
return self._total == other._total and self._elements == other._elements
if isinstance(other, (set, frozenset)):
pass
elif not isinstance(other, Set):
return NotImplemented
if self._total != len(other):
return False
return self._issubset(other, False)
def __ne__(self, other):
if isinstance(other, BaseMultiset):
return self._total != other._total or self._elements != other._elements
if isinstance(other, (set, frozenset)):
pass
elif not isinstance(other, Set):
return NotImplemented
if self._total != len(other):
return True
return not self._issubset(other, False)
def get(self, element, default):
"""Return the multiplicity for *element* if it is in the multiset, else *default*.
Makes the *default* argument of the original :meth:`dict.get` non-optional.
Args:
element: The element of which to get the multiplicity.
default: The default value to return if the element if not in the multiset.
Returns:
The multiplicity for *element* if it is in the multiset, else *default*.
"""
return self._elements.get(element, default)
@classmethod
def from_elements(cls, elements, multiplicity):
"""Create a new multiset with the given *elements* and each multiplicity set to *multiplicity*.
Uses :meth:`dict.fromkeys` internally.
Args:
elements: The element for the new multiset.
multiplicity: The multiplicity for all elements.
Returns:
The new multiset.
"""
return cls(dict.fromkeys(elements, multiplicity))
def copy(self):
"""Return a shallow copy of the multiset."""
return self.__class__(self)
__copy__ = copy
def items(self):
return self._elements.items()
def distinct_elements(self):
return self._elements.keys()
def multiplicities(self):
return self._elements.values()
values = multiplicities
@classmethod
def _as_multiset(cls, other):
if isinstance(other, BaseMultiset):
return other
if isinstance(other, _all_basic_types):
pass
elif not isinstance(other, Iterable):
raise TypeError("'%s' object is not iterable" % type(other)) # pragma: no cover
return cls(other)
@staticmethod
def _as_mapping(iterable):
if isinstance(iterable, BaseMultiset):
return iterable._elements
if isinstance(iterable, dict):
return iterable
if isinstance(iterable, _all_basic_types):
pass # create dictionary below
elif isinstance(iterable, Mapping):
return iterable
elif not isinstance(iterable, Iterable):
raise TypeError("'%s' object is not iterable" % type(iterable))
mapping = dict()
for element in iterable:
if element in mapping:
mapping[element] += 1
else:
mapping[element] = 1
return mapping
def __getstate__(self):
return self._total, self._elements
def __setstate__(self, state):
self._total, self._elements = state
class Multiset(BaseMultiset):
"""The mutable multiset variant."""
__slots__ = ()
def __setitem__(self, element, multiplicity):
"""Set the element's multiplicity.
This will remove the element if the multiplicity is less than or equal to zero.
'"""
if not isinstance(multiplicity, int):
raise TypeError('multiplicity must be an integer')
_elements = self._elements
if element in _elements:
old_multiplicity = _elements[element]
if multiplicity > 0:
_elements[element] = multiplicity
self._total += multiplicity - old_multiplicity
else:
del _elements[element]
self._total -= old_multiplicity
elif multiplicity > 0:
_elements[element] = multiplicity
self._total += multiplicity
def __delitem__(self, element):
_elements = self._elements
if element in _elements:
self._total -= _elements[element]
del _elements[element]
else:
raise KeyError("Could not delete {!r} from the multiset, because it is not in it.".format(element))
def update(self, *others):
r"""Like :meth:`dict.update` but add multiplicities instead of replacing them.
>>> ms = Multiset('aab')
>>> ms.update('abc')
>>> sorted(ms)
['a', 'a', 'a', 'b', 'b', 'c']
Note that the operator ``+=`` is equivalent to :meth:`update`, except that the operator will only
accept sets to avoid accidental errors.
>>> ms += Multiset('bc')
>>> sorted(ms)
['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c']
For a variant of the operation which does not modify the multiset, but returns a new
multiset instead see :meth:`combine`.
Args:
others: The other sets to add to this multiset. Can also be any :class:`~typing.Iterable`\[~T]
or :class:`~typing.Mapping`\[~T, :class:`int`] which are then converted to :class:`Multiset`\[~T].
"""
_elements = self._elements
for other in map(self._as_mapping, others):
for element, multiplicity in other.items():
self[element] += multiplicity
def union_update(self, *others):
r"""Update the multiset, adding elements from all others using the maximum multiplicity.
>>> ms = Multiset('aab')
>>> ms.union_update('bc')
>>> sorted(ms)
['a', 'a', 'b', 'c']
You can also use the ``|=`` operator for the same effect. However, the operator version
will only accept a set as other operator, not any iterable, to avoid errors.
>>> ms = Multiset('aab')
>>> ms |= Multiset('bccd')
>>> sorted(ms)
['a', 'a', 'b', 'c', 'c', 'd']
For a variant of the operation which does not modify the multiset, but returns a new
multiset instead see :meth:`union`.
Args:
others: The other sets to union this multiset with. Can also be any :class:`~typing.Iterable`\[~T]
or :class:`~typing.Mapping`\[~T, :class:`int`] which are then converted to :class:`Multiset`\[~T].
"""
_elements = self._elements
_total = self._total
for other in map(self._as_mapping, others):
for element, multiplicity in other.items():
old_multiplicity = _elements.get(element, 0)
if multiplicity > old_multiplicity:
_elements[element] = multiplicity
_total += multiplicity - old_multiplicity
self._total = _total
def __ior__(self, other):
if isinstance(other, (BaseMultiset, set, frozenset)):
pass
elif not isinstance(other, Set):
return NotImplemented
self.union_update(other)
return self
def intersection_update(self, *others):
r"""Update the multiset, keeping only elements found in it and all others.
>>> ms = Multiset('aab')
>>> ms.intersection_update('bc')
>>> sorted(ms)
['b']
You can also use the ``&=`` operator for the same effect. However, the operator version
will only accept a set as other operator, not any iterable, to avoid errors.
>>> ms = Multiset('aabc')
>>> ms &= Multiset('abbd')
>>> sorted(ms)
['a', 'b']
For a variant of the operation which does not modify the multiset, but returns a new
multiset instead see :meth:`intersection`.
Args:
others: The other sets to intersect this multiset with. Can also be any :class:`~typing.Iterable`\[~T]
or :class:`~typing.Mapping`\[~T, :class:`int`] which are then converted to :class:`Multiset`\[~T].
"""
for other in map(self._as_mapping, others):
for element, current_count in list(self.items()):
multiplicity = other.get(element, 0)
if multiplicity < current_count:
self[element] = multiplicity
def __iand__(self, other):
if isinstance(other, (BaseMultiset, set, frozenset)):
pass
elif not isinstance(other, Set):
return NotImplemented
self.intersection_update(other)
return self
def difference_update(self, *others):
r"""Remove all elements contained the others from this multiset.
>>> ms = Multiset('aab')
>>> ms.difference_update('abc')
>>> sorted(ms)
['a']
You can also use the ``-=`` operator for the same effect. However, the operator version
will only accept a set as other operator, not any iterable, to avoid errors.
>>> ms = Multiset('aabbbc')
>>> ms -= Multiset('abd')
>>> sorted(ms)
['a', 'b', 'b', 'c']
For a variant of the operation which does not modify the multiset, but returns a new
multiset instead see :meth:`difference`.
Args:
others: The other sets to remove from this multiset. Can also be any :class:`~typing.Iterable`\[~T]
or :class:`~typing.Mapping`\[~T, :class:`int`] which are then converted to :class:`Multiset`\[~T].
"""
for other in map(self._as_multiset, others):
for element, multiplicity in other.items():
self.discard(element, multiplicity)
def __isub__(self, other):
if isinstance(other, (BaseMultiset, set, frozenset)):
pass
elif not isinstance(other, Set):
return NotImplemented
self.difference_update(other)
return self
def symmetric_difference_update(self, other):
r"""Update the multiset to contain only elements in either this multiset or the other but not both.
>>> ms = Multiset('aab')
>>> ms.symmetric_difference_update('abc')
>>> sorted(ms)
['a', 'c']
You can also use the ``^=`` operator for the same effect. However, the operator version
will only accept a set as other operator, not any iterable, to avoid errors.
>>> ms = Multiset('aabbbc')
>>> ms ^= Multiset('abd')
>>> sorted(ms)
['a', 'b', 'b', 'c', 'd']
For a variant of the operation which does not modify the multiset, but returns a new
multiset instead see :meth:`symmetric_difference`.
Args:
other: The other set to take the symmetric difference with. Can also be any :class:`~typing.Iterable`\[~T]
or :class:`~typing.Mapping`\[~T, :class:`int`] which are then converted to :class:`Multiset`\[~T].
"""
other = self._as_multiset(other)
elements = set(self.distinct_elements()) | set(other.distinct_elements())
for element in elements:
multiplicity = self[element]
other_count = other[element]
self[element] = (multiplicity - other_count if multiplicity > other_count else other_count - multiplicity)
def __ixor__(self, other):
if isinstance(other, (BaseMultiset, set, frozenset)):
pass
elif not isinstance(other, Set):
return NotImplemented
self.symmetric_difference_update(other)
return self
def times_update(self, factor):
"""Update each this multiset by multiplying each element's multiplicity with the given scalar factor.
>>> ms = Multiset('aab')
>>> ms.times_update(2)
>>> sorted(ms)
['a', 'a', 'a', 'a', 'b', 'b']
You can also use the ``*=`` operator for the same effect:
>>> ms = Multiset('ac')
>>> ms *= 3
>>> sorted(ms)
['a', 'a', 'a', 'c', 'c', 'c']
For a variant of the operation which does not modify the multiset, but returns a new
multiset instead see :meth:`times`.
Args:
factor: The factor to multiply each multiplicity with.
"""
if factor < 0:
raise ValueError("The factor must not be negative.")
elif factor == 0:
self.clear()
else:
_elements = self._elements
for element in _elements:
_elements[element] *= factor
self._total *= factor
def __imul__(self, factor):
if not isinstance(factor, int):
raise TypeError("factor must be an integer.")
self.times_update(factor)
return self
def add(self, element, multiplicity=1):
"""Adds an element to the multiset.
>>> ms = Multiset()
>>> ms.add('a')
>>> sorted(ms)
['a']
An optional multiplicity can be specified to define how many of the element are added:
>>> ms.add('b', 2)
>>> sorted(ms)
['a', 'b', 'b']
This extends the :meth:`MutableSet.add` signature to allow specifying the multiplicity.
Args:
element:
The element to add to the multiset.
multiplicity:
The multiplicity i.e. count of elements to add.
"""
if multiplicity < 1:
raise ValueError("Multiplicity must be positive")
self._elements[element] += multiplicity
self._total += multiplicity
def remove(self, element, multiplicity=None):
"""Removes an element from the multiset.
If no multiplicity is specified, the element is completely removed from the multiset:
>>> ms = Multiset('aabbbc')
>>> ms.remove('a')
2
>>> sorted(ms)
['b', 'b', 'b', 'c']
If the multiplicity is given, it is subtracted from the element's multiplicity in the multiset:
>>> ms.remove('b', 2)
3
>>> sorted(ms)
['b', 'c']
It is not an error to remove more elements than are in the set:
>>> ms.remove('b', 2)
1
>>> sorted(ms)
['c']
This extends the :meth:`MutableSet.remove` signature to allow specifying the multiplicity.
Args:
element:
The element to remove from the multiset.
multiplicity:
An optional multiplicity i.e. count of elements to remove.
Returns:
The multiplicity of the element in the multiset before
the removal.
Raises:
KeyError: if the element is not contained in the set. Use :meth:`discard` if
you do not want an exception to be raised.
"""
_elements = self._elements
if element not in _elements:
raise KeyError
old_multiplicity = _elements.get(element, 0)
if multiplicity is None or multiplicity >= old_multiplicity:
del _elements[element]
self._total -= old_multiplicity
elif multiplicity < 0:
raise ValueError("Multiplicity must be not be negative")
elif multiplicity > 0:
_elements[element] -= multiplicity
self._total -= multiplicity
return old_multiplicity
def discard(self, element, multiplicity=None):
"""Removes the `element` from the multiset.
If multiplicity is ``None``, all occurrences of the element are removed:
>>> ms = Multiset('aab')
>>> ms.discard('a')
2
>>> sorted(ms)
['b']
Otherwise, the multiplicity is subtracted from the one in the multiset and the
old multiplicity is removed:
>>> ms = Multiset('aab')
>>> ms.discard('a', 1)
2
>>> sorted(ms)
['a', 'b']
In contrast to :meth:`remove`, this does not raise an error if the