Popcorn Hacks
Popcorn Hack #1: Dice Roll Simulation (Basic)
Objective: Write a function that simulates a 6-sided dice roll using the random module.
import random
def roll_dice():
return random.randint(1, 6)
print("Dice roll:", roll_dice())
Dice roll: 4
Popcorn Hack #2: Biased Color Generator
Objective: Modify the function biased_color() so that:
- Red appears 50% of the time
- Blue appears 30% of the time
- All other colors share the remaining 20%
Then print 10 random biased colors.
import random
def biased_color():
colors = ["red", "blue", "purple", "green", "yellow", "black", "white", "pink", "orange", "magenta"]
probabilities = [0.5, 0.3, 0.025, 0.025, 0.025, 0.025, 0.025, 0.025, 0.025, 0.025]
return random.choices(colors, probabilities)[0]
for _ in range(10):
print("Color:", biased_color())
Color: red
Color: pink
Color: red
Color: blue
Color: blue
Color: magenta
Color: blue
Color: blue
Color: black
Color: red
Practice MC
1 (Frog question): C
2018 Q18: C
Homework Hacks
Homework Hack #1- Coin Flip Win Simulation
Objective: Simulate a game where two players flip a coin. First to reach 3 heads wins.
Task:
- Use random.choice() to simulate flipping a coin (“heads” or “tails”).
- Each player flips once per round.
- Track how many heads each player has.
- Stop when one player reaches 3 heads.
- Print the winner and how many rounds it took.
import random
def coin_flip():
return random.choice(["heads", "tails"])
def play_game():
player1_heads = 0
player2_heads = 0
rounds = 0
while player1_heads < 3 and player2_heads < 3:
rounds += 1
print(f"\nRound {rounds}:")
# Player 1 flip
p1_flip = coin_flip()
print(f"Player 1 flip: {p1_flip}")
if p1_flip == "heads":
player1_heads += 1
p2_flip = coin_flip()
print(f"Player 2 flip: {p2_flip}")
if p2_flip == "heads":
player2_heads += 1
print(f"Score -> Player 1: {player1_heads} heads, Player 2: {player2_heads} heads")
if player1_heads == 3:
print(f"\nPlayer 1 wins in {rounds} rounds!")
else:
print(f"\nPlayer 2 wins in {rounds} rounds!")
play_game()
Round 1:
Player 1 flip: heads
Player 2 flip: heads
Score -> Player 1: 1 heads, Player 2: 1 heads
Round 2:
Player 1 flip: heads
Player 2 flip: heads
Score -> Player 1: 2 heads, Player 2: 2 heads
Round 3:
Player 1 flip: heads
Player 2 flip: heads
Score -> Player 1: 3 heads, Player 2: 3 heads
Player 1 wins in 3 rounds!