jeudi 20 septembre 2018

python random sample for samples larger than population

I have a list of integers which represent the number of applications submitted per day for a 60 day period. I need to randomly generate a list of 288 integers that sum to the number of applications per day. I have the following code:

import random as r

issued = [1000,200,344...]
def random_sum_to(n, num_terms = None):
    num_terms = (num_terms or r.randint(2, n)) - 1
    a = r.sample(range(1, n), num_terms) + [0, n]
    list.sort(a)
    return [a[i+1] - a[i] for i in range(len(a) - 1)]

for i in issued:
    print(random_sum_to(i,288))

Where issued is the list of integers that are the sum of the applications submitted per day. This code works great for numbers greater than 288 but crashes for numbers less than 288. Reading on here i saw that random.choice should be used but I cannot figure out how to implement it correctly. Looking at the results it looks like 0 is never printed so that is clearly a potential source for the problem. Any suggestions?




Aucun commentaire:

Enregistrer un commentaire