<jupyter_start><jupyter_text>有一堆彩色球， 红黄蓝绿紫等等， 现在给你一个概率的list/dict, 比方说红20%， 黄30%， 蓝50%， 你给我写个程序抽球(sample)。Sampling from a huge number of colored balls<jupyter_code>prob = {'red': 0.2, 'yellow': 0.3, 'blue': 0.5}
# The colors (groups) of a bag of balls may or maynot be the same as the keys of prob
colors = ['red', 'yellow', 'blue'] 
# function to pick the ball with certain probality
import numpy as np
def pick_ball(colors, num, prob):
    return np.random.choice(colors, num, prob)
for i in range(10):
    print(pick_ball(colors, 1, prob)[0])
def pick_n_balls(n):
    balls = {}
    while n > 0:
        color = pick_ball(colors, 1, prob)[0]
        balls[color] = balls.get(color, 0) + 1
        n-=1
    return balls
pick_n_balls(1000)<jupyter_output><empty_output><jupyter_text>numpy.random.sample<jupyter_code>np.random.random_sample()
np.random.sample()
np.random.random_sample(4)
np.random.random_sample((4, 1))
np.random.sample((1, 4))<jupyter_output><empty_output><jupyter_text>random int from low and high, inclusive<jupyter_code>np.random.random_integers(5, size=(3,2))
np.random.randint(5, size=(3,2)) #high (exclusive).<jupyter_output><empty_output><jupyter_text>use random.random() or random.choice()<jupyter_code># use random.random() 
import random
prob = [('red', 0.2), ('yellow', 0.3), ('blue', 0.5)]
# get a number between (0, 0.2), (0.2, 0.5), (0.5, 1)

# function to pick the ball with specified probality for each colors
def pick_a_ball(prob):
    randint_rng = []
    upper = 0
    lower = 0
    for i, x in enumerate(prob):
        lower = upper
        upper += x[1] # map the probability to a range.
        randint_rng.append((x[0], lower, upper))
#     print(f'ball\'s color and its range: {randint_rng}')
    # pick the ball with a random number
    num = random.random()
    for rng in randint_rng:
        if rng[1] <= num < rng[2]:
            return rng[0]
pick_a_ball(prob)
res = []
for i in range(10000):
    res.append(pick_a_ball(prob))
    
from collections import Counter
Counter(res)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1450827653359299, 'fraction_numerical': 0.03164556962025317, 'mean_word_length': 4.124688279301745, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 18, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '526503', 'license': 'MIT', 'n_tokens_mistral': 823, 'n_tokens_neox': 801, 'n_words': 202, 'path': 'sampling color balls.ipynb', 'repo_name': 'zhensongren/learn-python', 'size': '2054'}