I am trying to calculate the number of possible combinations to add up to a single value using every number just once in Python 2.7.
For example for 7 this would be 6+1, 5+2, 4+3, 4+2+1 --> 4 possible combinations
I managed to forge this into a recursive function that does the math right
import time
counter_list = []
def start(n):
tic=time.time()
recursive_step(range(1, n), n)
toc=time.time()
print(toc - tic)
return len(counter_list)
def recursive_step(numbers, target, summe=0):
if summe == target:
counter_list.append(1)
if summe >= target:
return
for i in xrange(len(numbers)):
n = numbers[i]
remaining = numbers[i+1:]
recursive_step(remaining, target, summe + n)
if __name__ == "__main__":
print(start(7))
Unfortunally it becomes very slow when the numbers become bigger. Following are some numbers I meassured on my machine.
~~~ 40 ~~~
time in seconds: 0.0789999961853
possible combinations: 1112
~~~ 50 ~~~
time in seconds: 0.40299987793
possible combinations: 3657
~~~ 60 ~~~
time in seconds: 1.51200008392
possible combinations: 10879
~~~ 70 ~~~
time in seconds: 5.41400003433
possible combinations: 29926
~~~ 80 ~~~
time in seconds: 18.388999939
possible combinations: 77311
~~~ 90 ~~~
time in seconds: 54.5920000076
possible combinations: 189585
I have looked into dynamic programming principles. But I could not get it to work on that Problem. Any advice on how I can improve that script would be greatly appreciated