/
bagging.py
1039 lines (818 loc) · 36 KB
/
bagging.py
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
# Copyright 2009-2015 Ram Rachum.
# This program is distributed under the MIT license.
import operator
import heapq
import itertools
import numbers
import collections
import functools
import copy
from python_toolbox import misc_tools
from python_toolbox import math_tools
from .lazy_tuple import LazyTuple
from .ordered_dict import OrderedDict
from .various_ordered_sets import FrozenOrderedSet
from .various_frozen_dicts import FrozenDict, FrozenOrderedDict
from .abstract import Ordered, DefinitelyUnordered
class _NO_DEFAULT(misc_tools.NonInstantiable):
'''Stand-in value used in `_BaseBagMixin.pop` when no default is wanted.'''
class _ZeroCountAttempted(Exception):
'''
An attempt was made to add a value with a count of zero to a bag.
This exception is used only internally for flow control; it'll be caught
internally and the zero item would be silently removed.
'''
def _count_elements_slow(mapping, iterable):
'''Put elements from `iterable` into `mapping`.'''
mapping_get = mapping.get
for element in iterable:
mapping[element] = mapping_get(element, 0) + 1
try:
from _collections import _count_elements
except ImportError:
_count_elements = _count_elements_slow
def _process_count(count):
'''Process a count of an item to ensure it's a positive `int`.'''
if not math_tools.is_integer(count):
raise TypeError(
'You passed %s as a count, while a `Bag` can only handle integer '
'counts.' % repr(count)
)
if count < 0:
raise TypeError(
"You passed %s as a count, while `Bag` doesn't support negative "
"amounts." % repr(count)
)
if count == 0:
raise _ZeroCountAttempted
return int(count)
class _BootstrappedCachedProperty(misc_tools.OwnNameDiscoveringDescriptor):
'''
A property that is calculated only once for an object, and then cached.
This is redefined here in `bagging.py`, in addition to having it defined in
`python_toolbox.caching`, because we can't import the canonical
`CachedProperty` from there because of an import loop.
Usage:
class MyObject:
# ... Regular definitions here
def _get_personality(self):
print('Calculating personality...')
time.sleep(5) # Time consuming process that creates personality
return 'Nice person'
personality = _BootstrappedCachedProperty(_get_personality)
You can also put in a value as the first argument if you'd like to have it
returned instead of using a getter. (It can be a tobag static value like
`0`). If this value happens to be a callable but you'd still like it to be
used as a static value, use `force_value_not_getter=True`.
'''
def __init__(self, getter_or_value, doc=None, name=None,
force_value_not_getter=False):
'''
Construct the cached property.
`getter_or_value` may be either a function that takes the parent object
and returns the value of the property, or the value of the property
itself, (as long as it's not a callable.)
You may optionally pass in the name that this property has in the
class; this will save a bit of processing later.
'''
misc_tools.OwnNameDiscoveringDescriptor.__init__(self, name=name)
if callable(getter_or_value) and not force_value_not_getter:
self.getter = getter_or_value
else:
self.getter = lambda thing: getter_or_value
self.__doc__ = doc or getattr(self.getter, '__doc__', None)
def __get__(self, obj, our_type=None):
if obj is None:
# We're being accessed from the class itself, not from an object
return self
value = self.getter(obj)
setattr(obj, self.get_our_name(obj, our_type=our_type), value)
return value
def __call__(self, method_function):
'''
Decorate method to use value of `CachedProperty` as a context manager.
'''
from python_toolbox import decorator_tools
def inner(same_method_function, self_obj, *args, **kwargs):
with getattr(self_obj, self.get_our_name(self_obj)):
return method_function(self_obj, *args, **kwargs)
return decorator_tools.decorator(inner, method_function)
def __repr__(self):
return '<%s: %s>' % (type(self).__name__, self.our_name or self.getter)
class _BaseBagMixin:
'''
Mixin for `FrozenBag` and `FrozenOrderedBag`.
Most of the bag functionality is implemented here, with a few finishing
touches in the classes that inherit from this. This mixin is used both for
ordered, unordered, frozen and mutable bags, so only the methods that are
general to all of them are implemented here.
'''
def __init__(self, iterable={}):
super().__init__()
if isinstance(iterable, collections.Mapping):
for key, value, in iterable.items():
try:
self._dict[key] = _process_count(value)
except _ZeroCountAttempted:
continue
else:
_count_elements(self._dict, iterable)
__getitem__ = lambda self, key: self._dict.get(key, 0)
def most_common(self, n=None):
'''
List the `n` most common elements and their counts, sorted.
Results are sorted from the most common to the least. If `n is None`,
then list all element counts.
>>> Bag('abcdeabcdabcaba').most_common(3)
(('a', 5), ('b', 4), ('c', 3))
'''
if n is None:
return tuple(sorted(self.items(), key=operator.itemgetter(1),
reverse=True))
return tuple(heapq.nlargest(n, self.items(),
key=operator.itemgetter(1)))
@property
def elements(self):
'''
Iterate over elements repeating each as many times as its count.
>>> c = Bag('ABCABC')
>>> tuple(c.elements)
('A', 'B', 'A', 'B', 'C', 'C')
'''
return itertools.chain.from_iterable(
itertools.starmap(itertools.repeat, self.items())
)
def __contains__(self, item):
return (self[item] >= 1)
n_elements = property(
lambda self: sum(self.values()),
doc='''Number of total elements in the bag.'''
)
@property
def frozen_bag_bag(self):
'''
A `FrozenBagBag` of this bag.
This means, a bag where `3: 4` means "The original bag has 4 different
keys with a value of 3."
Example:
>>> bag = Bag('abracadabra')
>>> bag
Bag({'b': 2, 'r': 2, 'a': 5, 'd': 1, 'c': 1})
>>> bag.frozen_bag_bag
FrozenBagBag({1: 2, 2: 2, 5: 1})
'''
from .frozen_bag_bag import FrozenBagBag
return FrozenBagBag(self.values())
def __or__(self, other):
'''
Make a union bag of these two bags.
The new bag will have, for each key, the higher of the two amounts for
that key in the two original bags.
Example:
>>> Bag('abbb') | Bag('bcc')
Bag({'b': 3, 'c': 2, 'a': 1})
'''
if not isinstance(other, _BaseBagMixin):
return NotImplemented
return type(self)(self._dict_type(
(key, max(self[key], other[key]))
for key in FrozenOrderedSet(self) | FrozenOrderedSet(other))
)
def __and__(self, other):
'''
Make an intersection bag of these two bags.
The new bag will have, for each key, the lower of the two amounts for
that key in the two original bags.
Example:
>>> Bag('abbb') & Bag('bcc')
Bag({'b': 1,})
'''
if not isinstance(other, _BaseBagMixin):
return NotImplemented
return type(self)(self._dict_type(
(key, min(self[key], other[key]))
for key in FrozenOrderedSet(self) & FrozenOrderedSet(other))
)
def __add__(self, other):
'''
Make a sum bag of these two bags.
The new bag will have, for each key, the sum of the two amounts for
that key in each of the two original bags.
Example:
>>> Bag('abbb') + Bag('bcc')
Bag({'b': 4, 'c': 2, 'a': 1})
'''
if not isinstance(other, _BaseBagMixin):
return NotImplemented
return type(self)(self._dict_type(
(key, self[key] + other[key])
for key in FrozenOrderedSet(self) | FrozenOrderedSet(other))
)
def __sub__(self, other):
'''
Get the subtraction of one bag from another.
This creates a new bag which has the items of the first bag minus the
items of the second one. Negative counts are truncated to zero: If
there are any items in the second bag that are more than the items in
the first bag, the result for that key will simply be zero rather than
a negative amount.
'''
if not isinstance(other, _BaseBagMixin):
return NotImplemented
return type(self)(self._dict_type(
(key, max(self[key] - other[key], 0)) for key in self)
)
def __mul__(self, other):
'''Get a new bag that has all counts multiplied by the integer `other`.'''
if not math_tools.is_integer(other):
return NotImplemented
return type(self)(self._dict_type((key, count * other) for
key, count in self.items()))
__rmul__ = lambda self, other: self * other
def __floordiv__(self, other):
'''
Do a floor-division `self // other`.
`other` can be either an integer or a bag.
If `other` is an integer, the result will be the biggest bag possible
so that `result * other <= self`.
If `other` is a bag, the result will be the maximum number of times you
can put `other` inside of `self` without having it surpass `self` for
any key. (Or in other words, the biggest integer possible so that
`result * other <= self`.)
'''
if math_tools.is_integer(other):
return (
type(self)(self._dict_type((key, count // other) for
key, count in self.items()))
)
elif isinstance(other, _BaseBagMixin):
for key in other:
if key not in self:
assert other[key] >= 1
return 0
division_results = []
for key in self:
if other[key] >= 1:
division_results.append(self[key] // other[key])
if division_results:
return min(division_results)
else:
raise ZeroDivisionError
else:
return NotImplemented
def __mod__(self, other):
'''
Do a modulo `self % other`.
`other` can be either an integer or a bag.
If `other` is an integer, the result will be a bag with `% other` done
on the count of every item from `self`. Or you can also think of it as
`self - (self // other)`, which happens to be the same bag.
If `other` is a bag, the result will be the bag that's left when you
subtract as many copies of `other` from this bag, until you can't
subtract without truncating some keys. Or in other words, it's `self -
(self // other)`.
'''
if math_tools.is_integer(other):
return (
type(self)(self._dict_type((key, count % other) for
key, count in self.items()))
)
elif isinstance(other, _BaseBagMixin):
return divmod(self, other)[1]
else:
return NotImplemented
def __divmod__(self, other):
'''
Get `(self // other, self % other)`.
If `other` is an integer, the first item of the result will be the
biggest bag possible so that `result * other <= self`. The second item
will be a bag with `% other` done on the count of every item from
`self`, or you can also think of it as `self - (self // other)`, which
happens to be the same bag.
If `other` is a bag, the first item of the result will be the maximum
number of times you can put `other` inside of `self` without having it
surpass `self` for any key. (Or in other words, the biggest integer
possible so that `result * other <= self`.) The second item will be the
result of the first item subtracted from `self`.
'''
if math_tools.is_integer(other):
return (
type(self)(self._dict_type((key, count // other) for
key, count in self.items())),
type(self)(self._dict_type((key, count % other) for
key, count in self.items())),
)
elif isinstance(other, _BaseBagMixin):
floordiv_result = self // other
mod_result = type(self)(
self._dict_type((key, count - other[key] * floordiv_result) for
key, count in self.items())
)
return (floordiv_result, mod_result)
else:
return NotImplemented
def __pow__(self, other, modulo=None):
'''Get a new bag with every item raised to the power of `other`.'''
if not math_tools.is_integer(other):
return NotImplemented
if modulo is None:
return type(self)(self._dict_type((key, count ** other) for
key, count in self.items()))
else:
return type(self)(self._dict_type(
(key, pow(count, other, modulo)) for
key, count in self.items())
)
__bool__ = lambda self: any(True for element in self.elements)
###########################################################################
### Defining comparison methods: ##########################################
# #
# We define all the comparison methods manually instead of using
# `total_ordering` because `total_ordering` assumes that >= means (> and
# ==) while we, in `FrozenOrderedBag`, don't have that hold because ==
# takes the items' order into account. Yes, my intelligence and sense of
# alertness know no bounds.
def __lt__(self, other):
'''
`self` is a strictly smaller bag than `other`.
That means that for every key in `self`, its count in `other` is bigger
or equal than in `self`-- And there's at least one key for which the
count in `other` is strictly bigger.
Or in other words: `set(self.elements) < set(other.elements)`.
'''
if not isinstance(other, _BaseBagMixin):
return NotImplemented
found_strict_difference = False # Until challenged.
all_elements = set(other) | set(self)
for element in all_elements:
if self[element] > other[element]:
return False
elif self[element] < other[element]:
found_strict_difference = True
return found_strict_difference
def __gt__(self, other):
'''
`self` is a strictly bigger bag than `other`.
That means that for every key in `other`, its count in `other` is smaller
or equal than in `self`-- And there's at least one key for which the
count in `other` is strictly smaller.
Or in other words: `set(self.elements) > set(other.elements)`.
'''
if not isinstance(other, _BaseBagMixin):
return NotImplemented
found_strict_difference = False # Until challenged.
all_elements = set(other) | set(self)
for element in all_elements:
if self[element] < other[element]:
return False
elif self[element] > other[element]:
found_strict_difference = True
return found_strict_difference
def __le__(self, other):
'''
`self` is smaller or equal to `other`.
That means that for every key in `self`, its count in `other` is bigger
or equal than in `self`.
Or in other words: `set(self.elements) <= set(other.elements)`.
'''
if not isinstance(other, _BaseBagMixin):
return NotImplemented
for element, count in self.items():
if count > other[element]:
return False
return True
def __ge__(self, other):
'''
`self` is bigger or equal to `other`.
That means that for every key in `other`, its count in `other` is bigger
or equal than in `self`.
Or in other words: `set(self.elements) >= set(other.elements)`.
'''
if not isinstance(other, _BaseBagMixin):
return NotImplemented
all_elements = set(other) | set(self)
for element in all_elements:
if self[element] < other[element]:
return False
return True
# #
### Finished defining comparison methods. #################################
###########################################################################
def __repr__(self):
if not self:
return '%s()' % type(self).__name__
return '%s(%s)' % (
type(self).__name__,
self._dict if self._dict else ''
)
__deepcopy__ = lambda self, memo: type(self)(
copy.deepcopy(self._dict, memo))
def __reversed__(self):
# Gets overridden in `_OrderedBagMixin`.
raise TypeError("Can't reverse an unordered bag.")
def get_contained_bags(self):
'''
Get all bags that are subsets of this bag.
This means all bags that have counts identical or smaller for each key.
'''
from python_toolbox import combi
keys, amounts = zip(*((key, amount) for key, amount in self.items()))
return combi.MapSpace(
lambda amounts_tuple:
type(self)(self._dict_type(zip(keys, amounts_tuple))),
combi.ProductSpace(map(lambda amount: range(amount+1), amounts))
)
class _MutableBagMixin(_BaseBagMixin):
'''Mixin for a bag that's mutable. (i.e. not frozen.)'''
def __setitem__(self, i, count):
try:
super().__setitem__(i, _process_count(count))
except _ZeroCountAttempted:
del self[i]
def setdefault(self, key, default=None):
'''
Get value of `key`, unless it's zero/missing, if so set to `default`.
'''
current_count = self[key]
if current_count > 0:
return current_count
else:
self[key] = default
return default
def __delitem__(self, key):
# We're making `__delitem__` not raise an exception on missing or
# zero-count elements because we're automatically deleting zero-count
# elements even though they seem to exist from the outside, so we're
# avoiding raising exceptions where someone would try to explicitly
# delete them.
try:
del self._dict[key]
except KeyError:
pass
def pop(self, key, default=_NO_DEFAULT):
'''
Remove `key` from the bag, returning its value.
If `key` is missing and `default` is given, returns `default`.
'''
value = self[key]
if value == 0 and default is not _NO_DEFAULT:
return default
else:
del self[key]
return value
def __ior__(self, other):
'''
Make this bag into a union bag of this bag and `other`.
After the operation, this bag will have, for each key, the higher of
the two amounts for that key in the two original bags.
>>> bag = Bag('abbb')
>>> bag |= Bag('bcc')
>>> bag
Bag({'b': 3, 'c': 2, 'a': 1})
'''
if not isinstance(other, _BaseBagMixin):
return NotImplemented
for key, other_count in tuple(other.items()):
self[key] = max(self[key], other_count)
return self
def __iand__(self, other):
'''
Make this bag into an intersection bag of this bag and `other`.
After the operation, this bag will have, for each key, the lower of the
two amounts for that key in the two original bags.
>>> bag = Bag('abbb')
>>> bag &= Bag('bcc')
>>> bag
Bag({'b': 1,})
'''
if not isinstance(other, _BaseBagMixin):
return NotImplemented
for key, count in tuple(self.items()):
self[key] = min(count, other[key])
return self
def __iadd__(self, other):
'''
Make this bag into a sum bag of this bag and `other`.
After the operation, this bag will have, for each key, the sum of the
two amounts for that key in each of the two original bags.
Example:
>>> bag = Bag('abbb')
>>> bag += Bag('bcc')
>>> bag
Bag({'b': 4, 'c': 2, 'a': 1})
'''
if not isinstance(other, _BaseBagMixin):
return NotImplemented
for key, other_count in tuple(other.items()):
self[key] += other_count
return self
def __isub__(self, other):
'''
Subtract `other` from this bag.
This reduces the count of each key in this bag by its count in `other`.
Negative counts are truncated to zero: If there are any items in the
second bag that are more than the items in the first bag, the result
for that key will simply be zero rather than a negative amount.
'''
if not isinstance(other, _BaseBagMixin):
return NotImplemented
for key, other_count in tuple(other.items()):
self[key] = max(self[key] - other_count, 0)
return self
def __imul__(self, other):
'''Multiply all the counts in this bag by the integer `other`.'''
if not math_tools.is_integer(other):
return NotImplemented
for key in tuple(self):
self[key] *= other
return self
def __ifloordiv__(self, other):
'''
Make this bag into a floor-division `self // other`.
`other` can be either an integer or a bag.
If `other` is an integer, this bag will have all its counts
floor-divided by `other`. (You can also think of it as: This bag will
become the biggest bag possible so that if you multiply it by `other`,
it'll still be smaller or equal to its old `self`.)
If `other` is a bag, the result will be the maximum number of times you
can put `other` inside of `self` without having it surpass `self` for
any key. (Or in other words, the biggest integer possible so that
`result * other <= self`.) Since this result is an integer rather than
a bug, the result variable will be set to it but this bag wouldn't
really be modified.
'''
if not math_tools.is_integer(other):
return NotImplemented
for key in tuple(self):
self[key] //= other
return self
def __imod__(self, other):
'''
Make this bag int a modulo `self % other`.
`other` can be either an integer or a bag.
If `other` is an integer, the result will have all its counts modulo-ed
by `other`. Or you can also think of it as becoming the bag `self -
(self // other)`, which happens to be the same bag.
If `other` is a bag, the result will be the bag that's left when you
subtract as many copies of `other` from this bag, until you can't
subtract without truncating some keys. Or in other words, it's `self -
(self // other)`. Since this result is an integer rather than
a bug, the result variable will be set to it but this bag wouldn't
really be modified.
'''
if math_tools.is_integer(other):
for key in tuple(self):
self[key] %= other
return self
elif isinstance(other, _BaseBagMixin):
floordiv_result = self // other
self %= floordiv_result
return self
else:
return NotImplemented
def __ipow__(self, other, modulo=None):
'''Raise each count in this bag to the power of `other`.'''
if not math_tools.is_integer(other):
return NotImplemented
for key in tuple(self):
self[key] = pow(self[key], other, modulo)
return self
def popitem(self):
'''
Pop an item from this bag, returning `(key, count)` and removing it.
'''
return self._dict.popitem()
def get_frozen(self):
'''Get a frozen version of this bag.'''
return self._frozen_type(self)
class _OrderedBagMixin(Ordered):
'''
Mixin for a bag that's ordered.
Items will be ordered according to insertion order. In every interface
where items from this bag are iterated on, they will be returned by their
order.
'''
__reversed__ = lambda self: reversed(self._dict)
def __eq__(self, other):
'''
Is this bag equal to `other`?
Order *does* count, so if `other` has a different order, the result
will be `False`.
'''
if type(self) != type(other):
return False
for item, other_item in itertools.zip_longest(self.items(),
other.items()):
if item != other_item:
return False
else:
return True
index = misc_tools.ProxyProperty(
'._dict.index',
doc='Get the index number of a key in the bag.'
)
class _FrozenBagMixin:
'''Mixin for a bag that's frozen. (i.e. can't be changed, is hashable.)'''
# Some properties are redefined here to be cached, since the bag is frozen
# and they can't change anyway, so why not cache them.
n_elements = _BootstrappedCachedProperty(
lambda self: sum(self.values()),
doc='''Number of total elements in the bag.'''
)
@_BootstrappedCachedProperty
def frozen_bag_bag(self):
'''
A `FrozenBagBag` of this bag.
This means, a bag where `3: 4` means "The original bag has 4 different
keys with a value of 3."
Example:
>>> bag = Bag('abracadabra')
>>> bag
Bag({'b': 2, 'r': 2, 'a': 5, 'd': 1, 'c': 1})
>>> bag.frozen_bag_bag
FrozenBagBag({1: 2, 2: 2, 5: 1})
'''
from .frozen_bag_bag import FrozenBagBag
return FrozenBagBag(self.values())
def get_mutable(self):
'''Get a mutable version of this bag.'''
return self._mutable_type(self)
# Poor man's caching done here because we can't import
# `python_toolbox.caching` due to import loop:
_contained_bags = None
def get_contained_bags(self):
'''
Get all bags that are subsets of this bag.
This means all bags that have counts identical or smaller for each key.
'''
if self._contained_bags is None:
self._contained_bags = super().get_contained_bags()
return self._contained_bags
class _BaseDictDelegator(collections.MutableMapping):
'''
Base class for a dict-like object.
It has its `dict` functionality delegated to `self._dict` which actually
implements the `dict` functionality. Subclasses override `_dict_type` to
determine the type of `dict` to use. (Regular or ordered.)
'''
def __init__(self, dict=None, **kwargs):
self._dict = self._dict_type()
if dict is not None:
self.update(dict)
if len(kwargs):
self.update(kwargs)
def __len__(self): return len(self._dict)
def __getitem__(self, key):
if key in self._dict:
return self._dict[key]
if hasattr(self.__class__, '__missing__'):
return self.__class__.__missing__(self, key)
raise KeyError(key)
def __setitem__(self, key, item): self._dict[key] = item
def __delitem__(self, key): del self._dict[key]
def __iter__(self):
return iter(self._dict)
def __contains__(self, key):
return key in self._dict
def __repr__(self): return repr(self._dict)
def copy(self):
if self.__class__ is _OrderedDictDelegator:
return _OrderedDictDelegator(self._dict.copy())
import copy
data = self._dict
try:
self._dict = self._dict_type()
c = copy.copy(self)
finally:
self._dict = data
c.update(self)
return c
@classmethod
def fromkeys(cls, iterable, value=None):
d = cls()
for key in iterable:
d[key] = value
return d
class _OrderedDictDelegator(Ordered, _BaseDictDelegator):
'''
An `OrderedDict`-like object.
It has its `OrderedDict` functionality delegated to `self._dict` which is
an actual `OrderedDict`.
'''
_dict_type = OrderedDict
index = misc_tools.ProxyProperty(
'._dict.index',
doc='Get the index number of a key in this dict.'
)
move_to_end = misc_tools.ProxyProperty(
'._dict.move_to_end',
doc='Move a key to the end (or start by passing `last=False`.)'
)
sort = misc_tools.ProxyProperty(
'._dict.sort',
doc='Sort the keys in this dict. (With optional `key` function.)'
)
class _DictDelegator(DefinitelyUnordered, _BaseDictDelegator):
'''
A `dict`-like object.
It has its `dict` functionality delegated to `self._dict` which is an
actual `dict`.
'''
_dict_type = dict
class Bag(_MutableBagMixin, _DictDelegator):
'''
A bag that counts items.
This is a mapping between items and their count:
>>> Bag('aaabcbc')
Bag({'a': 3, 'b': 2, 'c': 2})
It can be created from either an iterable like above, or from a `dict`.
This class provides a lot of methods that `collections.Counter` doesn't;
among them are a plethora of arithmetic operations (both between bags and
bags and between bags and integers), comparison methods between bags, and
more. This class is also more restricted than `collections.Counter`; only
positive integers may be used as counts (zeros are weeded out), so we don't
need to deal with all the complications of non-numerical counts.
'''
class OrderedBag(_OrderedBagMixin, _MutableBagMixin, _OrderedDictDelegator):
'''
An ordered bag that counts items.
This is a ordered mapping between items and their count:
>>> OrderedBag('aaabcbc')
OrderedBag((('a', 3), ('b', 2), ('c', 2)))
It can be created from either an iterable like above, or from a `dict`.
This class provides a lot of methods that `collections.Counter` doesn't;
among them are a plethora of arithmetic operations (both between bags and
bags and between bags and integers), comparison methods between bags, and
more. This class is also more restricted than `collections.Counter`; only
positive integers may be used as counts (zeros are weeded out), so we don't
need to deal with all the complications of non-numerical counts.
Also, unlike `collections.Counter`, items are ordered by insertion order.
(Simliarly to `collections.OrderedDict`.)
'''
def popitem(self, last=True):
'''
Pop an item from this bag, returning `(key, count)` and removing it.
By default, the item will be popped from the end. Pass `last=False` to
pop from the start.
'''
return self._dict.popitem(last=last)
move_to_end = misc_tools.ProxyProperty(
'._dict.move_to_end',
doc='Move a key to the end (or start by passing `last=False`.)'
)
sort = misc_tools.ProxyProperty(
'._dict.sort',
doc='Sort the keys in this bag. (With optional `key` function.)'
)
@property
def reversed(self):
'''Get a version of this `OrderedBag` with key order reversed.'''
return type(self)(self._dict_type(reversed(tuple(self.items()))))
class FrozenBag(_BaseBagMixin, _FrozenBagMixin, FrozenDict):
'''
An immutable bag that counts items.
This is an immutable mapping between items and their count:
>>> FrozenBag('aaabcbc')
FrozenBag({'a': 3, 'b': 2, 'c': 2})
It can be created from either an iterable like above, or from a `dict`.
This class provides a lot of methods that `collections.Counter` doesn't;
among them are a plethora of arithmetic operations (both between bags and
bags and between bags and integers), comparison methods between bags, and
more. This class is also more restricted than `collections.Counter`; only
positive integers may be used as counts (zeros are weeded out), so we don't
need to deal with all the complications of non-numerical counts.
Also, unlike `collections.Counter`, it's immutable, therefore it's also
hashable, and thus it can be used as a key in dicts and sets.
'''
def __hash__(self):
return hash((type(self), frozenset(self.items())))
class FrozenOrderedBag(_OrderedBagMixin, _FrozenBagMixin, _BaseBagMixin,
FrozenOrderedDict):
'''