1

I want to write a function which gives me a combination of numbers (with the given number of them) as a coefficients, that sum of them gives us 4.

Let's say the given variable number is 2. So we need to say find combination of a+b=4. It'll be [1,3], [2,2], [3,1], [0,4], [4,0]. Or if the given variable number is 3, so need to find combination of a+b+c=4 which will be [1,2,1], [1,1,2], etc.

How can I do this?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65

2 Answers2

0

The problem you are trying to solve is referred in Number Theory as Integer Partitioning. Refer to this answer for a possible solution. This math exchange might also help you to understand more about the math behind the problem.

-2

You can use this code

def combinations(iterable, r):
# combinations('ABCD', 2) --> AB AC AD BC BD CD
# combinations(range(4), 3) --> 012 013 023 123
pool = tuple(iterable)
n = len(pool)
if r > n:
    return
indices = list(range(r))
yield tuple(pool[i] for i in indices)
while True:
    for i in reversed(range(r)):
        if indices[i] != i + n - r:
            break
    else:
        return
    indices[i] += 1
    for j in range(i+1, r):
        indices[j] = indices[j-1] + 1
    yield tuple(pool[i] for i in indices)
amy
  • 23
  • 8
  • 1
    Thanks a lot! And How can I check if their sum is 4 or not? – idontwanttobehereanymore Jan 10 '21 at 23:56
  • 2
    (1) This code is just taken from https://docs.python.org/3/library/itertools.html#itertools.combinations without proper attribution (2) it's not formatted correctly (3) it doesn't solve the problem asked for in the question – mkrieger1 Jan 11 '21 at 00:06