Random country generator with population bias - Apple R1
  1. Building the Cumulative Weights ArrayBefore picking a country, Python transforms your relative population weights into a running total (prefix sum).If your data is:
    Iceland: 1 million
    USA: 340 million
    India: 1,428 million

Python internally builds a cumulative array:
Cumulative Weights=[1, 341, 1769]

  1. Generating a Uniform Random Floating Point

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))

  1. Binary Search Lookup

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.

  • Iteration 1:
    • low = 0, high = 4
    • mid = (0 + 4) // 2 = 2
    • Value at cumulative_weights[2] is 581
    • Is 450.0 >= 581? No.
    • Shift pointer: high = mid (which is 2) [1, 2, 3, 4, 5]
  • Iteration 2:
    • low = 0, high = 2
    • mid = (0 + 2) // 2 = 1
    • Value at cumulative_weights[1] is 341
    • Is 450.0 >= 341? Yes.
    • Shift pointer: low = mid + 1 (which is 2) [1, 2, 3]
  • Loop Ends:
    • low = 2, high = 2. The loop condition low < high fails.
    • The algorithm returns index 2. [1, 2]
      Index 2 maps perfectly to the 3rd country in your original list.

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}")
Comments (2)