Created
August 12, 2021 12:06
-
-
Save mwleeds/8cbff3483aa92c0c196511c165867dd1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import deque | |
import random | |
import os | |
class Card: | |
def __init__(self, suit, val): | |
self.suit = suit | |
self.value = val | |
# good practice is to include repr and str magic methods - that way you can print meaningful info | |
def __repr__(self): | |
return '<{} {}>'.format(self.value, self.suit) | |
class Deck: | |
def __init__(self): | |
# use deque - it's more efficient to pop from left than from a list -> good advice -> learn build in types :) | |
self.cards = deque() | |
self.build() | |
def build(self): | |
self.cards.clear() | |
for suit in ["Hearts", "Diamonds", "Spades", "Clubs"]: | |
for value in range(1, 14): | |
self.cards.append(Card(suit, value)) | |
# need to shuffle in order to have random order of cards | |
random.shuffle(self.cards) | |
def length(self): | |
return len(self.cards) | |
def get_card(self): | |
return self.cards.popleft() | |
def __repr__(self): | |
return 'Deck: [{} Cards]'.format(self.length()) | |
NUM_ROUNDS = 1000000 | |
NUM_IN_KITTY = 7 | |
times_found_in_kitty = 0 | |
for i in range(NUM_ROUNDS): | |
deck = Deck() | |
found_jack_in_kitty = False | |
for j in range(NUM_IN_KITTY): | |
card = deck.get_card() | |
if card.suit == 'Diamonds' and card.value == 11: | |
found_jack_in_kitty = True | |
if found_jack_in_kitty: | |
times_found_in_kitty += 1 | |
random.seed(os.urandom(50)) | |
probability = (times_found_in_kitty / NUM_ROUNDS) * 100 | |
print('After {} rounds with a {} card kitty, a card was found {}% of the time'.format(NUM_ROUNDS, NUM_IN_KITTY, probability)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment