dimanche 25 avril 2021

Python - Random Values generation based on distribution

I need to create a simulation of case assignment in Python:

For each item in a list it needs to be assigned value from one of the below location based on the %age of cases that need to be assigned to each country.

Country Case Load
US 30%
UK 30%
India 30%
Singapore 10%

For example, if there are 100 items in a python list, each needs to be assigned to either of the countries in the list. For example, once the count of cases assigned to UK reaches 30, it needs to stop assigning US anymore.

distro = {'US': 0.3, 'UK': 0.3, 'India': 0.3, 'Singapore': 0.1}

locations = []
for key in distro.keys():
    locations.append(key)
locations

loc_assign = []
cases = 100

distro = {'US': 0.3, 'UK': 0.3, 'India': 0.3, 'Singapore': 0.1}

locations = []
for key in distro.keys():
    locations.append(key)
locations

for i in range(cases):
    a = random.choice(locations)
    if loc_assign.count(a) < distro.get(a):
        loc_assign.append(a)
    else:
        a = random.choice(locations)
        loc_assign.append(a)

But the output I am getting is below not correct:

US: 0.27
UK: 0.3
India: 0.22
Singapore: 0.21

How to I get this to arrive at the target distribution percentage.

I am fairly new to Python and can't figure this out. Any help would be appreciated.




Aucun commentaire:

Enregistrer un commentaire