samedi 10 avril 2021

Python: generate 5 random int (every has own range) with fixed sum

import random
#lets take kg(for Total) for better understanding

Total = random.randint(40, 110) #For example Total=100   kg and this is 100%

Total = (a+b+c+d+e) 
 

Each value in Total has own range (in %).

First: find random values (within ranges that is % from Total.).

I tried this (but sum() can be >or< than 100):

a=random.randint(40, 70)

b=random.randint(0, 4)

c=random.randint(0, 2)

d=random.randint(22, 44)

e=random.randint(0, 7)

Second:find exact value for a,b,c,d,e (according to the percentage from Total in First part). I tried this:

a=Total*random.randint(40, 70)/100

b=Total*random.randint(0, 4)/100

c=Total*random.randint(0, 2)/100

d=Total*random.randint(22, 44)/100

e=Total*random.randint(0, 7)/100

This code does not work. please help




Aucun commentaire:

Enregistrer un commentaire