# -------------------------------------- # Joy and Beauty of Data # John Paxton # June 1, 2017 # -------------------------------------- # Simulate dealing 2 BlackJack cards and # plotting the results. # -------------------------------------- import numpy as np import matplotlib.pyplot as plt # -------------------------------------- # evaluate # -------------------------------------- # card: a playing card represented by 0 - 51 # -------------------------------------- # Returns: the value of the card, an integer # -------------------------------------- # Aces count 11, Kings/Queens/Jacks count # 10, all other cards count face value. # -------------------------------------- def evaluate(card): if (2 <= card % 13 <= 10): # face value return card % 13 elif (card % 13 == 1): # ace return 11 else: # jack, queen or king return 10 # -------------------------------------- # generateAndScoreHand # -------------------------------------- # Returns: the value of 2 cards, an integer # -------------------------------------- # Randomly generate a 2-card BlackJack hand # from a regular 52 card deck and then determine # its value. # -------------------------------------- def generateAndScoreHand(): card1 = np.random.randint(52) card2 = np.random.randint(52) while (card1 == card2): # the cards must be different card2 = np.random.randint(52) value = evaluate(card1) + evaluate(card2) if (value == 22): # readjust score for 2 aces value = 12 return value # -------------------------------------- # generateHands # -------------------------------------- # howMany: the number of Blackjack hands to generate, an integer # -------------------------------------- # Returns: the values of each hand, a numpy array # -------------------------------------- def generateHands(howMany): result = np.ndarray([howMany], dtype='int') for hand in range(howMany): result[hand] = generateAndScoreHand() return result # -------------------------------------- # handCounts # -------------------------------------- # hands: the value of each 2-card BlackJack hand, a numpy array # -------------------------------------- # Hands can score 4 through 21. Determine and # print the number of hands for each value. # -------------------------------------- def handCounts(hands): counts = np.zeros([22], dtype=int) # slots 0 through 3 unused for hand in hands: counts[hand] += 1 for i in range(4, 22): print(i, counts[i]) # -------------------------------------- hands = generateHands(10000) handCounts(hands) plt.hist(hands, bins=np.arange(4, 23), normed=True, facecolor='red', align='left') # generate histogram plt.xticks(np.arange(4, 22)) plt.xlim(3.5, 21.5) plt.xlabel('Hand Value') plt.ylabel('Probability') plt.title('Histogram of 2-Card BlackJack Hands') plt.grid(True) plt.show()