Python: Generate matrix of Nx4 integers who sum is a constant
Question: I have search the web which has provided various solution on how to produce a
matrix of random numbers whose sum is a constant. My problem is slightly
different. I want to generate an NX4 matrix of exhaustive list of integers
such that sum of all numbers in the row is exactly 100. and integers have a
range from [0,100]. I want to the integers to increment sequentially as
opposed to random. How can I do it in Python?

Thank you.


Answer: `product` is a handy way of generating combinations

    
    
    In [774]: from itertools import product
    
    In [775]: [x for x in product(range(10),range(10)) if sum(x)==10]
    Out[775]: [(1, 9), (2, 8), (3, 7), (4, 6), (5, 5), (6, 4), (7, 3), (8, 2), (9, 1)]
    

The tuples sum to 10, and step sequentially (in the first value at least).

I can generalize it to 3 tuples, and it still runs pretty fast.

    
    
    In [778]: len([x for x in product(range(100),range(100),range(100)) if sum(x)==100])
    Out[778]: 5148
    

Length 4 tuples takes much longer (on an old machine),

    
    
    In [780]: len([x for x in product(range(100),range(100),range(100),range(100)) if sum(x)==100])
    Out[780]: 176847
    

So there's probably case to be made for solving this incrementally.

* * *
    
    
    [x for x in product(range(100),range(100),range(100)) if sum(x)<=100]
    

runs much faster, producing the same number of of 3 tuples (within 1 or 2).
And the 4th value can be derived that that `x`.

    
    
    In [790]: timeit len([x+(100-sum(x),) for x in product(range(100),range(100),range(100)) if sum(x)<=100])
    1 loops, best of 3: 444 ms per loop
    

