一對(Two of a kind)
現在來用模擬法估計機率。假設你受邀到朋友家打撲克牌。這個變體規則是每人發 5 張牌,牌型較好者獲勝。你將用模擬來估計抽到特定牌型的機率。我們先估計「至少有一對」的機率。一對(two of a kind)指的是你拿到 2 張花色不同、但數字相同的牌(例如:紅心 2、黑桃 2,再加上其他 3 張牌)。
完成本練習後,你會知道如何用模擬來計算撲克牌遊戲中的機率。
本練習屬於課程
Python 的統計模擬
練習說明
- 「發牌」:在 for 迴圈中,先將
deck_of_cards洗牌。接著選取前 5 張作為hand。 - 「計數數字」:使用
get()方法建立字典cards_in_hand,用來統計hand中每個numeric_value出現的次數。 - 「是否為一對?」檢查
cards_in_hand中的最大值是否大於或等於2,以判斷是否至少有一對。若是,將two_kind加一。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# 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))