测试5张牌手牌是否同花



我的目标是得到得到"flush"的概率

下面是我的代码:
from random import *
#generating deck
deck = []
for i in range(4):
for value in range(13):
deck.append(100*i + value)
sim = 100000

hearts = 0
spades = 0
diamonds = 0
clubs = 0
flush = 0
for i in range(sim):
#generating hand
hand = []
shuffle(deck)
for i in range(5):
hand.append(deck[i])
#checking for "flush"
for i in range(5):
if hand[i] < 100:
hearts += 1
elif hand[i] < 200:
spades += 1
elif hand[i] < 300:
diamonds += 1
elif hand[i] < 400:
clubs += 1
if hearts == 5 or spades == 5 or diamonds == 5 or clubs == 5:
flush += 1
#probability
print(flush/sim)

实际概率显然更接近0.03,但这不是得到的,代码中的逻辑是否有问题?

你可以利用itertools模块来做这件事:

from itertools import product
import random
suits = ['s', 'h', 'd', 'c']
cpips = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
deck = [c for c in product(cpips, suits)]  # combinations of suits and values
sim = 10000
flushes = 0
for s in sim:
random.shuffle(deck)
hand = []
for i in range(5):
hand.append(deck[i])
# check that all suits are matching
if all([hand[0][1] == c[1] for c in hand]):
flushes += 1
prob = flushes / sim

如果你想添加更多的随机性或使其更像纸牌游戏,你可以为其他玩家的数量创建一个参数p,并让i在每次迭代后增加那么多:

p = 5
for s in sim:
random.shuffle(deck)
hand = []
while len(hand) <=5:
hand.append(deck[i])
i += p
# check that all suits are matching
if all([hand[0][1] == c[1] for c in hand]):
flushes += 1

问题是您不会在每次迭代中将hearts,clubs,diamonds,spades重置为零。

你预期的大约0.03的结果也是错误的。同花顺的概率为:

12/51 * 11/50 * 10/49 * 9/48

第二张牌与第一张牌花色相同的概率是12/51,因为这副牌中还有51张牌,其中12张牌花色相同。用同样的推理,第三张牌是同样花色的概率是11/50,等等。

这个表达式的值约为0.00198

代码你的代码可以简化,如果你将省略卡片的排名部分,因为它在测量中没有作用。所以只要制作一副牌,每张牌有13张牌,没有等级指示。

该手牌可以用random.sample取,然后可以通过取该手牌的set来完成同花顺检查:如果它的大小为1,则它是同花顺:

from random import sample
sim = 100000
# generating deck with only suits
deck = [i for i in range(4) for value in range(13)]
flush = sum(1 for _ in range(sim) if len(set(sample(deck, 5))) == 1)
print(flush/sim)  # ~ 0.002

相关内容

  • 没有找到相关文章

最新更新