Skip to content

Commit

Permalink
Add __rsub__ and values()
Browse files Browse the repository at this point in the history
  • Loading branch information
wheerd committed Apr 13, 2018
1 parent c7a3690 commit 1f00239
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
7 changes: 7 additions & 0 deletions multiset.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,11 @@ def __sub__(self, other):
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.
Expand Down Expand Up @@ -614,6 +619,8 @@ def distinct_elements(self):
def multiplicities(self):
return self._elements.values()

values = multiplicities

@classmethod
def _as_multiset(cls, other):
if isinstance(other, BaseMultiset):
Expand Down
24 changes: 23 additions & 1 deletion tests/test_multiset.py
Original file line number Diff line number Diff line change
Expand Up @@ -589,6 +589,18 @@ def test_sub(MultisetCls):
assert result is not ms


def test_rsub(MultisetCls):
ms = MultisetCls('abc')

with pytest.raises(TypeError):
_ = 'abc' - ms

result = set('abd') - ms
assert sorted(result) == list('d')
assert isinstance(result, MultisetCls)
assert result is not ms


@pytest.mark.parametrize(
' initial, other, expected',
[
Expand Down Expand Up @@ -985,4 +997,14 @@ def test_str():
def test_repr():
ms = Multiset('aabc')

assert repr(ms) == "Multiset({'a': 2, 'b': 1, 'c': 1})"
assert repr(ms) == "Multiset({'a': 2, 'b': 1, 'c': 1})"


def test_multiplicities(MultisetCls):
ms = MultisetCls('aaabbc')
assert sorted(ms.multiplicities()) == [1, 2, 3]


def test_distinct_elements(MultisetCls):
ms = MultisetCls('aaabbc')
assert sorted(ms.distinct_elements()) == list('abc')

0 comments on commit 1f00239

Please sign in to comment.