python 一个袋子里有10个红色和20个绿色的弹珠,抽5个不放回,抽到2个红色和3个绿色的概率是多少?

xwbd5t1u  于 2023-02-07  发布在  Python
关注(0)|答案(1)|浏览(192)

我知道如何计算出画出相同颜色弹珠的概率,但我不知道如何编码得到2个红色和3个绿色。

random.seed(42)

total = 0
trials = 10000

for _ in range(trials):
    
    draw = random.sample(range(1,31),5)
    
    if (max(draw) <= 20) or ((min(draw) > 20 and max(draw) < 30)):
        total += 1
        
total/trials
t1qtbnec

t1qtbnec1#

每次尝试(每次你抽5颗弹珠)你都需要计算红色和绿色的数量。如果正好2颗是红色,3颗是绿色,增加你的total计数器。

import random

random.seed(42)

total = 0
trials = 10000

for _ in range(trials):

    red = 0
    green = 0

    draw = random.sample(range(1, 31), 5)
    for m in draw:
        if m <= 10:
            # we'll say marbles 1-10 are red, 11-30 are green
            red += 1
        else:
            green += 1

    if red == 2 and green == 3:
        total += 1

print(total / trials)

相关问题