Python internally builds a cumulative array:
Cumulative Weights=[1, 341, 1769]
Python picks a random floating-point number, X, uniformly scaled between zero and the total weight sum: 0 < X<1769
Every country now owns a continuous segment on this numeric timeline proportional to its population size.
Iceland owns the tiny range ([0, 1))
USA owns the range ([1, 341))
India owns the massive range ([341, 1769))
To find where your random number X lands, Python does not loop through the array from the beginning.
Instead, it uses the bisect module to perform a binary search over the sorted cumulative weights array.
If X = 0.4, it falls in the first bucket → Iceland.
If X = 500.2, it falls in the third bucket → India.
Because binary search divides the search space in half each step, finding the correct country takes (\mathcal{O}(\log N)) time.
Let's use an array of 4 countries with these internal cumulative weights:
[1, 341, 581, 2009]
Assume Python picks a random number target_x = 450.0.
N to build cumulative weights array
log N to do BS
total ~ O(N)
import random
def get_weighted_random_country(country_data):
"""
Selects a country randomly, biased by its population.
:param country_data: Dict where keys are country names and values are populations.
:return: String (The selected country name)
"""
# Extract names and their corresponding population weights
countries = list(country_data.keys())
populations = list(country_data.values())
# random.choices picks an item based on the provided weights array
# k=1 returns a list containing one element, so we extract it with [0]
selected_country = random.choices(countries, weights=populations, k=1)[0]
return selected_country
# Example Dataset
population_map = {
"India": 1428000000,
"China": 1425000000,
"United States": 340000000,
"Indonesia": 277000000,
"Pakistan": 240000000,
"Iceland": 390000
}
# Generate a biased random country
random_country = get_weighted_random_country(population_map)
print(f"Randomly selected country: {random_country}")