Skip to content

Instantly share code, notes, and snippets.

@erantapaa
Created November 18, 2015 16:28
Show Gist options
  • Save erantapaa/891c04d068fbf3edb575 to your computer and use it in GitHub Desktop.
Save erantapaa/891c04d068fbf3edb575 to your computer and use it in GitHub Desktop.
generating partitions
# Generator for partitions of an integer.
#
# See http://jeromekelleher.net/category/combinatorics.html
def ruleAsc(n):
a = [0 for i in range(n + 1)]
k = 1
a[1] = n
while k != 0:
x = a[k - 1] + 1
y = a[k] - 1
k -= 1
while x <= y:
a[k] = x
y -= x
k += 1
a[k] = x + y
yield a[:k + 1]
# yield partitions of n whose sizes are all >= m
def ruleAsc2(n,m):
a = [m-1 for i in range(n + 1)]
k = 1
a[1] = n-(m-1)
while k != 0:
# invariants:
# a[0] + a[1] + ... + a[k] == n
# a[0] <= a[1] <= ... <= a[k]
x = a[k - 1] + 1
y = a[k] - 1
k -= 1
while x <= y:
a[k] = x
y -= x
k += 1
a[k] = x + y
yield a[:k + 1]
def test1():
for p in ruleAsc2(15,1): print p
for p in ruleAsc2(15,2): print p
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment