一对
现在让我们用模拟来估计概率。假设您受邀去朋友家打扑克。在这个变体中,每位玩家发 5 张牌,牌型更好者获胜。您将用模拟来估计抽到某些牌型的概率。我们先来估计抽到「至少一对」的概率。「一对」指的是两张花色不同但点数相同的牌(例如红心 2、黑桃 2,再加上其他 3 张牌)。
完成本练习后,您将学会如何用模拟来计算纸牌游戏中的概率。
本练习是课程的一部分
Python 中的统计模拟
练习说明
- 发牌:在 for 循环中,先洗
deck_of_cards。然后取前 5 张作为hand。 - 统计点数:使用
get()方法构建字典cards_in_hand,统计hand中每个numeric_value出现的次数。 - 是否有一对?检查
cards_in_hand中的最大值是否大于等于2,以判断是否至少有一对。若是,则将two_kind加 1。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Shuffle deck & count card occurrences in the hand
n_sims, two_kind = 10000, 0
for i in range(n_sims):
____
hand, cards_in_hand = deck_of_cards[0:5], {}
for [suite, numeric_value] in hand:
# Count occurrences of each numeric value
cards_in_hand[numeric_value] = cards_in_hand.____(numeric_value, 0) + 1
# Condition for getting at least 2 of a kind
if ____ >=2:
two_kind += 1
print("Probability of seeing at least two of a kind = {} ".format(two_kind/n_sims))