Python Puzzles
In poker, the first person to be dealt an ace gets the role of dealer. Is the probability of being dealt the first ace equal for all players?
Create a simulation to find out.
Running a simulation, we find that the first person being dealt a card has a slightly higher percentage of being dealt the first ace.
After running 100,000 simulations, I get a 28% probability of the first person receiving the first ace.
Probability of Drawing an Ace:
Player 1: 27.89%
Player 2: 26.16%
Player 3: 21.83%
Player 4: 24.12%
import matplotlib.pyplot as plt
import random
from collections import Counter
result = []
loop = 100_000
for _ in range(loop):
#assume cards 1,2,3,4 are Aces
deck = list(range(1,53))
random.shuffle(deck)
#i represents the player, assuming there are 4 players
i = 1
#if the card is an ace, append the player (i) it was dealt to
for x in deck:
if x < 5:
result.append(i)
i = 1
break
else:
i +=1
#set i to player 1
if i > 4: i = 1
# equals to list(set(words))
keys = list(Counter(result).keys())
# counts the elements' frequency
values = list(Counter(result).values())
values_pct = []
# determine percent
for x in values:
values_pct.append(x/loop)
# sort the keys based on the values in descending order
keys = [k for _, k in sorted(zip(values, keys), reverse=True)]
# create a bar chart
plt.bar(keys, values_pct)
plt.ylabel("Percentage")
plt.xlabel("Player")
plt.title("Probability of Drawing an Ace\n")
plt.xticks(keys)
# Save the plot
plt.savefig('dealing-an-ace-barchart.png', dpi=300, bbox_inches='tight')
# Show the plot
plt.show()
# print the results in descending order
print("Probability of Drawing an Ace:\n")
for i, k in enumerate(keys):
print(f"Player {k}: {values_pct[i]:.2%}")
