Skip to content

Commit 1f00239

Browse files
committed
Add __rsub__ and values()
1 parent c7a3690 commit 1f00239

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

multiset.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,11 @@ def __sub__(self, other):
214214
return NotImplemented
215215
return self.difference(other)
216216

217+
def __rsub__(self, other):
218+
if not isinstance(other, (Set, BaseMultiset)):
219+
return NotImplemented
220+
return self._as_multiset(other).difference(self)
221+
217222
def union(self, *others):
218223
r"""Return a new multiset with all elements from the multiset and the others with maximal multiplicities.
219224
@@ -614,6 +619,8 @@ def distinct_elements(self):
614619
def multiplicities(self):
615620
return self._elements.values()
616621

622+
values = multiplicities
623+
617624
@classmethod
618625
def _as_multiset(cls, other):
619626
if isinstance(other, BaseMultiset):

tests/test_multiset.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -589,6 +589,18 @@ def test_sub(MultisetCls):
589589
assert result is not ms
590590

591591

592+
def test_rsub(MultisetCls):
593+
ms = MultisetCls('abc')
594+
595+
with pytest.raises(TypeError):
596+
_ = 'abc' - ms
597+
598+
result = set('abd') - ms
599+
assert sorted(result) == list('d')
600+
assert isinstance(result, MultisetCls)
601+
assert result is not ms
602+
603+
592604
@pytest.mark.parametrize(
593605
' initial, other, expected',
594606
[
@@ -985,4 +997,14 @@ def test_str():
985997
def test_repr():
986998
ms = Multiset('aabc')
987999

988-
assert repr(ms) == "Multiset({'a': 2, 'b': 1, 'c': 1})"
1000+
assert repr(ms) == "Multiset({'a': 2, 'b': 1, 'c': 1})"
1001+
1002+
1003+
def test_multiplicities(MultisetCls):
1004+
ms = MultisetCls('aaabbc')
1005+
assert sorted(ms.multiplicities()) == [1, 2, 3]
1006+
1007+
1008+
def test_distinct_elements(MultisetCls):
1009+
ms = MultisetCls('aaabbc')
1010+
assert sorted(ms.distinct_elements()) == list('abc')

0 commit comments

Comments
 (0)