Skip to content

Instantly share code, notes, and snippets.

@maxencefrenette
Last active January 23, 2026 20:54
Show Gist options
  • Select an option

  • Save maxencefrenette/94c34975cf0b96fa29b76fc403f07e85 to your computer and use it in GitHub Desktop.

Select an option

Save maxencefrenette/94c34975cf0b96fa29b76fc403f07e85 to your computer and use it in GitHub Desktop.
Card flip probability
from functools import cache
@cache
def p(black_cards_in_deck, red_cards_in_deck):
"""
You flip cards from a deck of cards.
At any point, you can stop and flip one last card.
If that card is black, you win. If it is red, you lose.
What is the probability of winning if you play optimally?
"""
if black_cards_in_deck == 0:
return 0
if red_cards_in_deck == 0:
return 1
black_cards_prop = black_cards_in_deck / (black_cards_in_deck + red_cards_in_deck)
red_cards_prop = red_cards_in_deck / (black_cards_in_deck + red_cards_in_deck)
return max(
# Option 1: Flip last card immediately
black_cards_in_deck / (black_cards_in_deck + red_cards_in_deck),
# Option 2: Flip last card after one more card
black_cards_prop * p(black_cards_in_deck - 1, red_cards_in_deck)
+ red_cards_prop * p(black_cards_in_deck, red_cards_in_deck - 1),
)
print(p(26, 26)) # 0.5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment