'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.
Solution 1:[1]
Here is a solution that more closely replicates your original approach. The biggest problem was that you need to multiply the distribution by the cases in your if statement. Also using a while loop is better in this case:
import random
distro = {'US': 0.3, 'UK': 0.3, 'India': 0.3, 'Singapore': 0.1}
loc_assign = []
cases = 100
i = 0
while i < cases:
a = random.choice(list(distro.keys()))
if loc_assign.count(a) < distro.get(a)* cases:
loc_assign.append(a)
i += 1
print(loc_assign.count('US')) #30
print(loc_assign.count('UK')) #30
print(loc_assign.count('India')) #30
print(loc_assign.count('Singapore')) #10
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | pakpe |
