Todd
Todd

Reputation: 439

generate random integers without replacement to obtain a fixed sum using n unique integers (Python)

As stated in the title, how do I generate random integers without replacement (each integer needs to be unique) to obtain a sum 1400 using 20 unique integers? but one constraint applied at the same time?
constraint: the range of each unique integer should be 1<= integer <=100

Upvotes: 0

Views: 65

Answers (1)

Kaavya Mahajan
Kaavya Mahajan

Reputation: 26

The following solution works but is very very inefficient. The numbers you are dealing with are small and so it won't take much time, but for larger numbers this will take too long.


import random
l = []
s = 1400

while True:
    x = random.randint(1,100)
    if x not in l:
        if (s - x) > 0:
            l.append(x)
            s -= x
        
        elif (s - x) == 0:
            l.append(x)
            s-=x
            print(l)
            break
        
        if len(l) >= 20:
            l = []
            s = 1400

Upvotes: 1

Related Questions