Simulation Blog
Simulation Blog Hacks
# Popcorn Hack #1
import random
def roll_dice():
def roll():
return random.randint(1, 6)
return roll()
print("Dice roll:", roll_dice())
Dice roll: 5
# Popcorn Hack #2
import random
def biased_color():
colors = ['Red', 'Blue', 'Green', 'Yellow', 'Purple']
probabilities = [0.5, 0.3, 0.05, 0.05, 0.1]
return random.choices(colors, probabilities)[0]
for _ in range(10):
print(biased_color())
Red
Blue
Blue
Red
Blue
Blue
Blue
Blue
Blue
Red
import random
# Homework Hack #1 - Coin Flip Win Simulation
def coin_flip_game():
player1_heads = 0
player2_heads = 0
rounds = 0
while player1_heads < 3 and player2_heads < 3:
rounds += 1
player1_flip = random.choice(["heads", "tails"])
player2_flip = random.choice(["heads", "tails"])
if player1_flip == "heads":
player1_heads += 1
if player2_flip == "heads":
player2_heads += 1
if player1_heads == 3:
print(f"Player 1 wins after {rounds} rounds!")
else:
print(f"Player 2 wins after {rounds} rounds!")
coin_flip_game()
Player 2 wins after 7 rounds!