This post contains some good python code to find all permutations in a set that sum up to some S. I would like to eliminate output gaps so that no element in the output line is more than 1 different from any adjacent line.
Here is the code to generate the output for which I want to order / sort:
def f(n,s): if n == 1: yield (s,) else: for i in xrange(s + 1): for j in f(n - 1,s - i): yield (i,) + j L = list(f(3,5)) for i in L: print i
Output:
(0, 0, 5) (0, 1, 4) (0, 2, 3) (0, 3, 2) (0, 4, 1) (0, 5, 0) (1, 0, 4) <-Bad, 0 transitioned to 4 from one row to the next (1, 1, 3) (1, 2, 2) (1, 3, 1) (1, 4, 0) (2, 0, 3) <-Bad, 4 transitioned to 0 from one row to the next (2, 1, 2) (2, 2, 1) (2, 3, 0) (3, 0, 2) (3, 1, 1) (3, 2, 0) (4, 0, 1) <-Bad, 2 transitioned to 0 from one row to the next (4, 1, 0) (5, 0, 0)
Desired Output: (0, 0, 5) (0, 1, 4) (0, 2, 3) (0, 3, 2) (0, 4, 1) (0, 5, 0) (1, 4, 0) (1, 3, 1) (1, 2, 2) (1, 1, 3) (1, 0, 4) (2, 0, 3) (2, 1, 2) (2, 2, 1) (2, 3, 0) (3, 2, 0) (3, 1, 1) (3, 0, 2) (4, 0, 1) (4, 1, 0) (5, 0, 0)
Can anyone suggest some code that will arrange the output in this way?