## Partitions

### May 11, 2012

The only tricky part is eliminating duplicates. Our solution is not to add the duplicates in the first place by defining a function `set-cons`

that is like cons but returns the original list unchanged if the item being consed onto the list is already present in the list:

`(define (set-cons x xs)`

(if (member x xs) xs

(cons x xs)))

With that, it’s easy. Two nested loops do the work; *x* loops over the integers from 1 to *n*, and `yss`

loops over the smaller partitions, calling `parts`

recursively:

`(define (parts n)`

(if (zero? n) (list (list))

(let ((xs (list)))

(do ((x 1 (+ x 1))) ((= x n) (cons (list n) xs))

(do ((yss (parts (- n x)) (cdr yss))) ((null? yss))

(set! xs (set-cons (sort < (cons x (car yss))) xs)))))))

We sort the lists so that duplicate lists in different orders can be identified and eliminated from the output. You may prefer this version of the function that eliminates the assignment:

`(define (parts n)`

(if (zero? n) (list (list))

(let x-loop ((x 1) (xs (list)))

(if (= x n) (cons (list n) xs)

(let y-loop ((yss (parts (- n x))) (xs xs))

(if (null? yss) (x-loop (+ x 1) xs)

(y-loop (cdr yss)

(set-cons (sort < (cons x (car yss)))

xs))))))))

Both versions of the function give the same output:

`> (parts 0)`

(())

> (parts 1)

((1))

> (parts 2)

((2) (1 1))

> (parts 3)

((3) (1 1 1) (1 2))

> (parts 4)

((4) (2 2) (1 1 2) (1 1 1 1) (1 3))

> (parts 5)

((5) (2 3) (1 1 3) (1 1 1 1 1) (1 1 1 2) (1 2 2) (1 4))

> (parts 6)

((6) (3 3) (2 2 2) (2 4) (1 1 4) (1 1 2 2) (1 1 1 1 2)

((1 1 1 1 1 1) (1 1 1 3) (1 2 3) (1 5))

You can run the program at http://programmingpraxis.codepad.org/TaCSCQAW.

A recursive solution in Clojure. The result is in the reverse order than what is shown in the problem description, because it’s slightly more convenient to check the subtrahend against 0 than against the original minuend, which would have to be remembered somehow. It shouldn’t matter as the problem calls for a set.

A copy-paste blunder. The code should read:

[sourceoode=”css”]

(defn- parts-helper [num subtr acc]

(cond

(= num 0) [acc]

(or (= subtr 0) (< num 0)) []

:else (concat

(parts-helper (- num subtr) subtr (conj acc subtr))

(parts-helper num (dec subtr) acc))))

(defn parts [num]

(parts-helper num num []))

[/sourcecode]

[…] today’s Programming Praxis exercise, our goal is to write a function that gives all unique sums that […]

My Haskell solution (see http://bonsaicode.wordpress.com/2012/05/11/programming-praxis-partitions/ for a version with comments):

Python 2.7

It strikes me that many recursive solutions will probably be inefficient

(except for Haskell ones, perhaps), since solutions to subproblems are

recomputed every time they’re needed, similar to SICP’s discussion of Fibonacci

number generation.

First up, a memoizing version (based on a Python version that Programming

Praxis pointed me to on StackOverflow) that stores previous answers.

Next are

`zs1`

and`zs2`

, Python versions of twoalgorithms found in

`Fast Algorithms for Generating Integer`

by Zoghbi and Stojmenovic (1998). They’re iterative and moreParitions

efficient than the first solution, if uglier. I’ve made them generators instead

of lists, but that’s not really relevant to the algorithms.

@Graham: The Haskell version isn’t memoized. Memoizing the function is pretty simple and doesn’t add too much to the program length though:

@Remco: thanks for that. I thought there might have been some sort of wizardry hidden in the lazy evaluation or something, but I appreciate the enlightenment.

Find partitions where the least term is equal to or greater than another parameter. This way duplicates are not generated. All partitions are found by setting the other parameter to 1.

Solution in Go:

This shows off some of the ugly things in Go: no built-in set type (use a map with an empty value), no easy way to get all the keys for a map (have to manually copy to a slice), no way to directly use a slice as the key for a map or define a custom hashcode or equals on a type (convert the slice to a string, and use that as the key in the map).

My solution is not as neat and elegant as yours but all the same, I’m proud that I was able to do it.

Here’s my solution in Python:

def partitions(n):

p = []

# n is not 0

if n:

# from 1 to n

for i in range(1, n+1):

a = partitions(n-i)

if len(a) == 0:

p.append(i)

else:

for j in a:

if isinstance(j, int):

b = [j, i]

b.sort()

if b not in p:

p.append(b)

else:

j.append(i)

j.sort()

if j not in p:

p.append(j)

return p

# n is 0

else:

return []

Another Python version [1].

It uses a sparse representation for the partitions, e.g., 4 = 4 x 1 = 2 x 1 + 2 = 1 x 1 + 3 = 2 x 2 = 1 x 4 instead of 4 = 1+1+1+1 = 1+1+2 = 1+3 = 2 + 2 = 4.

[1] http://code.activestate.com/recipes/221132/