Matching Cards in Two Decks

Python Puzzles

Back to the Python! homepage


If you shuffle two separate decks of cards, what is the probability of the same card appearing in the exact same position in the two separate decks?


Approximately 36% of the time the two decks will have zero matching cards in the same position; 64% of the time it will have at least one matching card. When I run the simulation 1 million times, the most matches I get is 9.


import random
from collections import Counter
import matplotlib.pyplot as plt
loop = 1_000_000
result_total = []

# ctreate a deck of cards
deck_of_cards1 = list(range(1,53))
deck_of_cards2 = list(range(1,53))

for _ in range(loop):

    random.shuffle(deck_of_cards1)
    random.shuffle(deck_of_cards2)
    result = []
    
    for d1, d2 in zip(deck_of_cards1, deck_of_cards2):
        if d1 == d2:
            result.append(1)    
    result_total.append(result.count(1))

result_total.sort()
keys = list(Counter(result_total).keys())
values = list(Counter(result_total).values())

values_pct = []
# determine percent
for x in values:
    values_pct.append(x/loop)

#create a bar chart
plt.bar(keys,values_pct)
plt.ylabel("Percentage")
plt.xlabel("# of Card Matches")
plt.title("Probability")
plt.xticks(keys)
plt.show()
values_pct.sort(reverse=True)
print(values_pct)