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
    # 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

# sort the result total list and count the number of occurrences of each value
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:

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

# print the sorted percentages in descending order