Skip to content

Instantly share code, notes, and snippets.

@ktbarrett
Last active January 19, 2019 04:24
Show Gist options
  • Save ktbarrett/34dd798b842b084e23d2d807408c27ca to your computer and use it in GitHub Desktop.
Save ktbarrett/34dd798b842b084e23d2d807408c27ca to your computer and use it in GitHub Desktop.
Python Multiset combinations
from collections import Counter as Multiset
def multiset_combinations(ms, n):
assert sum(ms.values()) >= n
def f(ms_res, curr_val, ms_rem):
nonlocal n
if sum(ms_res.values()) == n: #ideally len would return the number of total elements
yield ms_res
else:
for val in set(ms_rem):
if val >= curr_val:
# for each unique value in remaining multiset equal to or larger than the current value
val_ms = Multiset((val,)) # ideally I wouldn't need to wrap a singleton multiset
# add that value to the result multiset and remove it from remaining multiset
yield from f(ms_res + val_ms, val, ms_rem - val_ms)
# recurse
yield from f(Multiset(), sorted(ms.keys())[0], ms)
for m in multiset_combinations(Multiset((3, 3, 4, 4, 4, 5)), 3):
print(list(m.elements()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment