Skip to content

Commit 888c51b

Browse files
Counting integer partitions
1 parent 070ebb3 commit 888c51b

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
from __future__ import print_function
2+
3+
try:
4+
xrange #Python 2
5+
except NameError:
6+
xrange = range #Python 3
7+
8+
try:
9+
raw_input #Python 2
10+
except NameError:
11+
raw_input = input #Python 3
12+
13+
'''
14+
The number of partitions of a number n into at least k parts equals the number of partitions into exactly k parts
15+
plus the number of partitions into at least k-1 parts. Subtracting 1 from each part of a partition of n into k parts
16+
gives a partition of n-k into k parts. These two facts together are used for this algorithm.
17+
'''
18+
def partition(m):
19+
memo = [[0 for _ in xrange(m)] for _ in xrange(m+1)]
20+
for i in xrange(m+1):
21+
memo[i][0] = 1
22+
23+
for n in xrange(m+1):
24+
for k in xrange(1, m):
25+
memo[n][k] += memo[n][k-1]
26+
if n-k > 0:
27+
memo[n][k] += memo[n-k-1][k]
28+
29+
return memo[m][m-1]
30+
31+
if __name__ == '__main__':
32+
import sys
33+
34+
if len(sys.argv) == 1:
35+
try:
36+
n = int(raw_input('Enter a number: '))
37+
print(partition(n))
38+
except ValueError:
39+
print('Please enter a number.')
40+
else:
41+
try:
42+
n = int(sys.argv[1])
43+
print(partition(n))
44+
except ValueError:
45+
print('Please pass a number.')

0 commit comments

Comments
 (0)