Shuffled Card Deck

Python Puzzles

Back to the Python! homepage


Given a randomly shuffled deck of cards, where the numbered cards (1-10) are face value, the Ace is equal to 1, a Jack is equal to 11, a Queen is 12 and a King is 13.

What is the average number of cards in a shuffled deck that are in the correct numerical place?

For example, if an Ace is in the 1st, 14th, 27th, or 40th place in the deck, it would be considered in its proper numerical place.


On average, 4 cards will be in the correct numerical place.

You can also use the following equation to arrive at the answer.

52 * (1/13) = 4

import random
result = []

for _ in range(1_000_000):
    import random

result = []

for _ in range(1_000_000):
    
    i = 1
    match_count = 0

    # create a deck of cards with 3 sets of 13 cards (Ace to King)
    deck_of_cards = list(range(1,14))
    deck_of_cards += deck_of_cards
    deck_of_cards += deck_of_cards

    # shuffle the deck
    random.shuffle(deck_of_cards)
        
    for _ in range(52):
        
        # count the number of times the card matches the position
        if deck_of_cards[i-1] == i:
            match_count += 1
            
        # move to the next card and wrap around to the beginning of the deck if necessary
        i += 1
        if i == 14: i = 1    
        
    result.append(match_count)

# calculate and print the average number of matches
print(sum(result)/len(result))

    i = 1
    match_count = 0

    deck_of_cards = list(range(1,14))
    deck_of_cards += deck_of_cards
    deck_of_cards += deck_of_cards

    random.shuffle(deck_of_cards)
        
    for _ in range(52):
        
        if deck_of_cards[i-1] == i:
            match_count += 1
            
        i += 1
        if i == 14: i = 1    
        
    result.append(match_count)

#print(result)
print(sum(result)/len(result))