Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A nice way to find all combinations that give a sum of N?

Tags:

python

Is there a nice way for generating a list of digits (0-9), with repetitions and a length of 6, such that the sum is N, say, 20. For example:

004673 -> 4+6+7+3=20
121673 -> 1+2+1+6+7+3=20
...

Thanks

like image 869
Kar Avatar asked Dec 23 '11 15:12

Kar


People also ask

What is the easiest way to find all possible combinations?

To calculate combinations, we will use the formula nCr = n! / r! * (n - r)!, where n represents the total number of items, and r represents the number of items being chosen at a time. To calculate a combination, you will need to calculate a factorial.

How do you find the sum of combinations?

The sum of all possible combinations of n distinct things is 2 n. C0 + nC1 + nC2 + . . . + nC n = 2 n.

How do you find all the combinations that equal a sum in Python?

First, we take an empty list 'res' and start a loop and traverse each element of the given list of integers. In each iteration, pop the element, store it in 'num', find remaining difference for sum K, and check if the difference exists in the given list or not.


2 Answers

['{0:06}'.format(i) for i in xrange(1000000) if sum(map(int,str(i))) == 20]

does the trick and needs about 5 seconds to return all 35127 numbers.

UPDATE - as a bonus, here comes the ugly-but-much-faster (~40 times faster) version:

result = []
for a in xrange(10):
    for b in xrange(10):
        for c in xrange(10):
            if a+b+c <= 20:
                for d in xrange(10):
                    if 2 < a+b+c+d <= 20:
                        for e in xrange(10):
                            if 10 < a+b+c+d+e <= 20:
                                f = 20 - (a+b+c+d+e)
                                result.append(''.join(map(str, [a,b,c,d,e,f])))
like image 138
eumiro Avatar answered Oct 05 '22 23:10

eumiro


Much faster of other proposed solutions:

def iter_fun(sum, deepness, myString, Total):
    if deepness == 0:
        if sum == Total:
            print myString
    else:    
        for i in xrange(min(10, Total - sum + 1)):
            iter_fun(sum + i,deepness - 1,myString + str(i),Total) 

def fixed_sum_digits(digits, Tot):
    iter_fun(0,digits,"",Tot) 


fixed_sum_digits(6,20)

Still some room for speeder code but then the code would be boring to be read!

like image 37
jimifiki Avatar answered Oct 06 '22 01:10

jimifiki