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 = 100_000
result_total = []

# create two decks of cards with 52 cards each
deck_of_cards1 = list(range(1,53))
deck_of_cards2 = list(range(1,53))

for _ in range(loop):
    # shuffle both decks
    random.shuffle(deck_of_cards1)
    random.shuffle(deck_of_cards2)
    
    # compare cards of the same index in both decks
    result = []
    for d1, d2 in zip(deck_of_cards1, deck_of_cards2):
        if d1 == d2:
            result.append(1) # if two cards match, add 1 to the result list
            
    # append the count of matches to the result total list
    result_total.append(result.count(1))

# sort the result total list and count the number of occurrences of each value
result_total.sort()
keys = list(Counter(result_total).keys())
values = list(Counter(result_total).values())

# determine percentage of each value in the result total list
values_pct = []
for x in values:
    values_pct.append(x/loop)

# create a bar chart to show the distribution of results
plt.bar(keys,values_pct)
plt.ylabel("Percentage")
plt.xlabel("# of Card Matches")
plt.title("Probability")
plt.xticks(keys)
plt.savefig('matching-cards-two-decks-barchart.png', dpi=300, bbox_inches='tight')
plt.show()

# print the sorted percentages in descending order
values_pct.sort(reverse=True)
print(values_pct)