3

Given two integers n and d, I would like to construct a list of all nonnegative tuples of length d that sum up to n, including all permutations. This is similar to the integer partitioning problem, but the solution is much simpler. For example for d==3:

[
    [n-i-j, j, i]
    for i in range(n+1)
    for j in range(n-i+1)
]

This can be extended to more dimensions quite easily, e.g., d==5:

[
    [n-i-j-k-l, l, k, j, i]
    for i in range(n+1)
    for j in range(n-i+1)
    for k in range(n-i-j+1)
    for l in range(n-i-j-l+1)
]

I would now like to make d, i.e., the number of nested loops, a variable, but I'm not sure how to nest the loops then.

Any hints?

Nico Schlömer
  • 53,797
  • 27
  • 201
  • 249
  • I'm not sure if this is possible in a list comprehension as such but perhaps you could keep track of the subtracted values somehow so then all your loops look like `for val in range(n - sum(vals) + 1)` and then loop over that `d` times while building the list. – mattjegan Jul 27 '17 at 10:41
  • 3
    Possible duplicate of [Next Composition of n into k parts - does anyone have a working algorithm?](https://stackoverflow.com/questions/4647120/next-composition-of-n-into-k-parts-does-anyone-have-a-working-algorithm) – Nico Schlömer Aug 02 '17 at 12:12

1 Answers1

9

Recursion to the rescue: First create a list of tuples of length d-1 which runs through all ijk, then complete the list with another column n-sum(ijk).

def partition(n, d, depth=0):
    if d == depth:
        return [[]]
    return [
        item + [i]
        for i in range(n+1)
        for item in partition(n-i, d, depth=depth+1)
        ]


# extend with n-sum(entries)
n = 5
d = 3
lst = [[n-sum(p)] + p for p in partition(n, d-1)]

print(lst)
Nico Schlömer
  • 53,797
  • 27
  • 201
  • 249