Skip to the content.

Simulation/Games and Random Algorithms

Popcorn Hack 1

import random

def roll_dice():
    return random.randint(1, 6)

# print("Dice roll:", roll_dice())

Popcorn Hack 2

import random

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

    # Print 10 biased random colors
    for _ in range(10):
        print(random.choices(colors, probabilities)[0])

biased_color()
Red
Red
Yellow
Blue
Blue
Blue
Red
Blue
Red
Yellow

Homework Hack

import random

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

    while player1_heads < 3 and player2_heads < 3:
        rounds += 1
        # Player 1 flips the coin
        if random.choice(["heads", "tails"]) == "heads":
            player1_heads += 1
        # Player 2 flips the coin
        if random.choice(["heads", "tails"]) == "heads":
            player2_heads += 1

    if player1_heads == 3:
        print(f"Player 1 wins in {rounds} rounds!")
    else:
        print(f"Player 2 wins in {rounds} rounds!")

coin_flip_game()
Player 2 wins in 3 rounds!