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
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.
The sum of all possible combinations of n distinct things is 2 n. C0 + nC1 + nC2 + . . . + nC n = 2 n.
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.
['{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])))
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With