Skip to content

Commit

Permalink
Fix unnecessary sorting and copying in __hash__ (#52)
Browse files Browse the repository at this point in the history
* Fix unnecessary sorting and copying in __hash__

#51

* Use frozenset hash instead of summing

per feedback on #52 (review)

Co-authored-by: MikeFHay <>
  • Loading branch information
MikeFHay committed Dec 6, 2021
1 parent 0dba7f9 commit 16c8717
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 5 deletions.
3 changes: 1 addition & 2 deletions multiset.py
Original file line number Diff line number Diff line change
Expand Up @@ -1078,8 +1078,7 @@ class FrozenMultiset(BaseMultiset):
__slots__ = ()

def __hash__(self):
return hash(tuple(sorted(self._elements.items())))

return hash(frozenset(self._elements.items()))

Mapping.register(BaseMultiset) # type: ignore
MutableMapping.register(Multiset) # type: ignore
Expand Down
5 changes: 2 additions & 3 deletions tests/test_multiset.py
Original file line number Diff line number Diff line change
Expand Up @@ -968,11 +968,10 @@ def test_base_error():

def test_frozen_hash_equal():
ms1 = FrozenMultiset('ab')
ms2 = FrozenMultiset('ab')
ms2 = FrozenMultiset('ba')

assert hash(ms1) == hash(ms2)


def test_can_be_pickled():
fms = FrozenMultiset('aabcd')

Expand Down Expand Up @@ -1001,4 +1000,4 @@ def test_multiplicities(MultisetCls):

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

0 comments on commit 16c8717

Please sign in to comment.