samedi 14 janvier 2023

Py: random int distribution of numbers over [list] with exact sum

I'll be as concice as I can be.

I have a number generated by other means:

topic_interest_0 = 50 # this number is generated elsewhere

I have a list with a number of items, in this case 7:

topic_interest_literature = [0, 0, 0, 0, 0, 0, 0]

I need to distribute topic_interest_0 randomly over topic_interest_literature but where the sum of all items in topic_interest_literature is topic_interest_0 and no item is larger than 10.

I have tried a while loop:

while topic_interest_0 > 0:
            if topic_interest_0 >= 10:
                topic_interest_literature[0] = random.randint(0, 10)
            else:
                topic_interest_literature[0] = random.randint(0, topic_interest_0)
                
            topic_interest_0 -= topic_interest_literature[0]

And run this for every item in topic_interest_literature 0 to 6. But this is tedious since I have multiple other such lists to go through, plus it will always leave me with either a surplus or a deficit on the last possible random.




Aucun commentaire:

Enregistrer un commentaire