0
from itertools import product
import numpy as np

L = 3 N = 100
combination = np.tile(np.arange(1, N+1), [L, 1])

combine = product(*combination, repeat=1) 
number of placements with repetitions : 100^3 but we only need those that are equal to N
r = 0
for comb in combine:
    if sum(comb)==L:
        r += 1
r will be equal = 4851 but the number of operations will be = 1000000

How to optimize your code to avoid so many unnecessary repetitions?

Stef
  • 13,242
  • 2
  • 17
  • 28
  • If `L` is small compared to `N`, you can just set `r = list(range(1,L))` and then return `r + [N - sum(r)]]`. For instance for `L=4, N=100`, return `[1, 2, 3, 94]`. – Stef Dec 07 '20 at 13:59
  • 2
    Note that your question is inconsistent with your code. Your question specifically asks about *finding one combination* of numbers that have the correct sum. But your python code is *counting* a number of combinations. – Stef Dec 07 '20 at 14:01
  • 1
    Does this answer your question? [Find all combinations of a list of numbers with a given sum](https://stackoverflow.com/questions/34517540/find-all-combinations-of-a-list-of-numbers-with-a-given-sum) – Tomerikoo Dec 07 '20 at 14:09
  • Better duplicate with more detailed answer: [Finding all possible combinations of numbers to reach a given sum](https://stackoverflow.com/questions/4632322/finding-all-possible-combinations-of-numbers-to-reach-a-given-sum) – Stef Dec 07 '20 at 14:29

0 Answers0