Simulation and Random Algorithms - 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)

# Example usage:
print("Dice roll:", roll_dice())
Dice roll: 5

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 (e.g., Green, Yellow, Purple) share the remaining 20%

import random

def biased_color():
    colors = ["Red", "Blue", "Green", "Yellow", "Purple"]
    probabilities = [0.5, 0.3, 0.07, 0.07, 0.06]

    for _ in range(10):
        print("Color:", random.choices(colors, probabilities)[0])

# Example usage
biased_color()
Color: Red
Color: Red
Color: Blue
Color: Red
Color: Red
Color: Red
Color: Blue
Color: Red
Color: Red
Color: Purple

Homework Hack #1: Coin Flip Win Simulation

Objective:
Simulate a game where two players flip a coin. The first to reach 3 heads wins.

Steps:

  1. Use random.choice(["heads", "tails"]) for coin flips.
  2. Keep track of how many heads each player has.
  3. Loop until one player reaches 3 heads.
  4. Print the winner and how many rounds it took.

import random

def coin_flip_game():
    player1_heads = 0
    player2_heads = 0
    rounds = 0

    while player1_heads < 3 and player2_heads < 3:
        p1_flip = random.choice(["heads", "tails"])
        p2_flip = random.choice(["heads", "tails"])

        if p1_flip == "heads":
            player1_heads += 1
        if p2_flip == "heads":
            player2_heads += 1

        rounds += 1

    if player1_heads == 3:
        winner = "Player 1"
    else:
        winner = "Player 2"

    print(f"{winner} wins after {rounds} rounds!")

# Example usage
coin_flip_game()
Player 2 wins after 5 rounds!