[Solved] How to generate N integers (say 365) that sum up to some value K (say 20)? [duplicate]


Using random.randint and the condition where a new random is redrawn if sum(l) + r > 20 you can populate of 365 with a sum of 20,

import random

l = []
k = 20
n = 365

for i in range(n):
    if sum(l) > 20:
         l.append(0)
    else:
        r = random.randint(0,2)
        while sum(l) + r > k:
            r = random.randint(0,2)
        l.append(r)

Note

For further randomization of the list I would additionally shuffle it afterwards

random.shuffle(l)

print(sum(l))  # -> 20
print(len(l))  # -> 365

5

solved How to generate N integers (say 365) that sum up to some value K (say 20)? [duplicate]