Skip to content

Instantly share code, notes, and snippets.

@madmann91
Last active October 31, 2018 20:00
Show Gist options
  • Save madmann91/2bcd5373274c67419a923888bf9f624b to your computer and use it in GitHub Desktop.
Save madmann91/2bcd5373274c67419a923888bf9f624b to your computer and use it in GitHub Desktop.
Enumerate possible partitions of a set with M objects into N bins.
def insert(p, i, m, n):
q = []
for j in range(0, n):
if j == i:
s = set(p[j])
s.add(m)
q.append(s)
else:
q.append(p[j])
return q
def parts(n, m):
if n == 1:
return [[set(range(0, m))]]
if m == 1:
return [[set()] * (n - 1) + [set([0])]]
res = []
for p in parts(n, m - 1):
for i in range(0, n):
res.append(insert(p, i, m - 1, n))
return res
print(parts(2, 8))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment