#!/usr/bin/python3 # this program takes a number N as a command-line parameter and # prints all the *partitions* of N # # a partition of a positive number N is a set of positive numbers that # add up to N. For example, { 3, 2, 2 } is a partition of 7. # Also, for example, all the partitions of N=4 are: # # 4 # 3 1 # 2 2 # 2 1 1 # 1 1 1 1 # # P contains a lists of numbers and represents a previously computed # partition, say of a number X. n is the value of which we want to # find all partitions. For each one of these partitions Q, the # function partition() adds Q to P and prints the list, that is, a # partition of n+X. # # The key idea to partition n is to compose a non-increasing list of # numbers, which is intended to avoid repeating the same partition. # # Thus partition(n, limit, P) partitions n in parts that are not # greater than limit. # def partition(n, limit, P): # ASSERT(n >= limit) while limit > 0: P.append(limit) remainder = n - limit if remainder > limit: partition(remainder, limit, P) else: if remainder == 0: for n in P: print(n,end=' ') print() else: partition(remainder, remainder, P) del P[-1] limit -= 1 import sys if len(sys.argv) != 2: sys.stderr.write('usage: ' + sys.argv[0] + ' \n') exit(1) N = int(sys.argv[1]) partition(N, N, [])