Unknown Deck of Cards

Python Puzzles

Back to the Python! homepage


You process a deck with 50 cards that has an unknown and random number of red and black cards. What is the probability of drawing a red card from the deck?


The probability is 50%.

import random
import numpy as np

# initialize an empty deck list and a counter for red cards
deck = []
red = 0
size = 1_000_000

# generate a random number of red cards (0-51) for each iteration
# calculate the percentage of red cards and append a binomial distribution (0=black, 1=red) to the deck
for _ in range(size):
    number_red_cards = random.randrange(0,51)    
    pct_red = 0 if number_red_cards == 0 else number_red_cards/50
    deck.append(np.random.binomial(size=1, n=1, p=pct_red))    
     
# count the number of red cards in the deck
for x in deck:
    if x == 1: 
        red += 1

# print the probability of drawing a red card
print('The probability is ' + '{0:.2%}'.format(red/size))