Created
December 25, 2013 04:15
-
-
Save umrysh/8120106 to your computer and use it in GitHub Desktop.
Generate all combinations of integers that sum to 100
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Makes use of the "Most Efficient Algorithm" posted here: | |
# http://homepages.ed.ac.uk/jkellehe/partitions.php | |
import csv | |
def partitions(n): | |
a = [0 for i in range(n + 1)] | |
k = 1 | |
y = n - 1 | |
while k != 0: | |
x = a[k - 1] + 1 | |
k -= 1 | |
while 2*x <= y: | |
a[k] = x | |
y -= x | |
k += 1 | |
l = k + 1 | |
while x <= y: | |
a[k] = x | |
a[l] = y | |
yield a[:k + 2] | |
x += 1 | |
y -= 1 | |
a[k] = x + y | |
y = x + y - 1 | |
yield a[:k + 1] | |
f = csv.writer(open("partitions.csv", 'wb'), delimiter=',',quotechar='"', quoting=csv.QUOTE_MINIMAL) | |
generatedPartitions = partitions(100) | |
for i in generatedPartitions: | |
print i | |
f.writerow(i) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment