Skip to content

Instantly share code, notes, and snippets.

@Mr-Milk
Last active July 9, 2020 03:38
Show Gist options
  • Save Mr-Milk/74a9c700ed4c8f4e935af49dc57f1829 to your computer and use it in GitHub Desktop.
Save Mr-Milk/74a9c700ed4c8f4e935af49dc57f1829 to your computer and use it in GitHub Desktop.
A simple implementation of immutable multiset
from collections import Counter
class combs:
"""
A simple implementation of immutable multiset
"""
def __init__(self, seq):
s = set(seq)
if len(seq) == len(s):
self._save = s
self._unique = True
self._counts = Counter(s)
else:
self._save = tuple(seq)
self._unique = False
self._counts = Counter(seq)
def __eq__(self, comb):
if isinstance(comb, self.__class__):
return self.__dict__['_counts'] == comb.__dict__['_counts']
else:
return False
def __repr__(self):
return f"combs({', '.join([str(s) for s in self._save])})"
def __str__(self):
return ', '.join([str(s) for s in self._save])
def __iter__(self):
yield from self._save
def __hash__(self):
if self._unique:
return hash(frozenset(self._save))
else:
return hash(frozenset([(k, v) for k, v in self._counts.items()]))
def __dir__(self):
return dir(super(combs, self))[:-1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment