Random Algorithms
Popcorn Hacks
Popcorn Hack 1: Brainstorm
What do you think a random algorithm is? What would be reason to use random algorithms in real-life coding situations? What kind of questions do you think College Board will ask regarding Random Algorithms?
A random algorithm analyzes a list and picks a random option from that list. In a video game software, for example, to create an element of unpredictability, random algorithm can be implemented to simulate a dice roll or a card shuffle depending on what the game needs. College Board will probably ask about Missing Code segments in random algorithms and what needs to be inside.
Popcorn Hack 2
# Popcorn Hack Number 2 (Random): Make a random algorithm to choose a daily activity:
import random
# Step 1: Define a list of activities
activities = ['Play with dogs', 'Do homework', 'Hang out with friends', 'Go to the gym', 'Go out to dinner', 'Sleep', 'Go for a run', 'Bake something', 'Submit internship applications']
# Step 2: Randomly choose an activity
random_activity = random.choice(activities)
# Step 3: Display the chosen activity
print(f"Today’s random activity: {random_activity}")
Today’s random activity: Do homework
Popcorn Hack 3
# Popcorn Hack Number 3: Using a loops in random
# This popcorn hack assigns an activity to each person
import random
hosts = ['Claire', 'Mihir', 'Travis']
activities = ['code, code, code', 'food', 'drinks']
# Randomly shuffle the list of activities to assign them randomly to the guests
random.shuffle(activities)
# Loop through each guest and assign them a random activity
for i in range(len(hosts)):
print(f"{hosts[i]} will be monitoring {activities[i]}!")
Claire will be monitoring drinks!
Mihir will be monitoring code, code, code!
Travis will be monitoring food!
Simulations
Popcorn Hacks
Popcorn Hack 1
import random
def number_spinner():
return random.randint(1, 10)
number = number_spinner()
print("Number:", number)
Number: 2
Popcorn Hack 2
import random
def play_rock_paper_scissors():
choices = ['rock', 'paper', 'scissors']
computer_choice = random.choice(choices)
user_choice = input("Enter your choice (rock, paper, or scissors): ")
if user_choice not in choices:
print("Invalid choice. Please try again.")
return
print("Computer chose:", computer_choice)
print("You chose:", user_choice)
if user_choice == computer_choice:
print("It's a tie!")
elif (user_choice == 'rock' and computer_choice == 'scissors') or (user_choice == 'paper' and computer_choice == 'rock') or (user_choice == 'scissors' and computer_choice == 'paper'):
print("You win!")
else:
print("You lose!")
play_rock_paper_scissors()
Computer chose: paper
You chose: rock
You lose!
Output
- Computer - scissors, Me - paper: I lose
- Computer - paper, Me - paper: It’s a tie
- Computer - paper, Me - rock: I lose
Homework Hacks
Random Algorithms
Homework Hack 1
Objective: Randomly assign students to teams for a group project.
Task: You are given a list of 15 students.
The goal is to randomly assign each student to one of 3 teams (be creative with the names)
Implement the random assignment:
Randomly assign each student to a team
Print out the list of students and their assigned teams.
import random
students = ['Claire', 'Evelyn', 'Ryan', 'Jessica', 'Nicholas', 'Leo', 'Beau', 'Hannah', 'Katelyn',
'Kayla', 'Aadya', 'Dasom', 'Mickey', 'Minnie', 'Goofey']
teams = ['Giggle Gang', 'Tickle Team', 'Buff Buddies']
# Shuffle the students for random assignment
random.shuffle(students)
# Create a dictionary to store team assignments
team_assignments = {
'Giggle Gang': [],
'Tickle Team': [],
'Buff Buddies': []
}
# Assign students to teams in a round-robin way
for i, student in enumerate(students):
team = teams[i % 3]
team_assignments[team].append(student)
# Print out the assignments
for team, members in team_assignments.items():
print(f"\n{team}:")
for member in members:
print(f" - {member}")
Giggle Gang:
- Beau
- Dasom
- Mickey
- Nicholas
- Leo
Tickle Team:
- Hannah
- Evelyn
- Aadya
- Kayla
- Minnie
Buff Buddies:
- Goofey
- Ryan
- Jessica
- Claire
- Katelyn
Homework Hack 2
Objective: Generate random weather patterns over a set number of days.
Task: You’re simulating the weather for a 7-day forecast.
The weather each day can be one of three options: Sunny, Cloudy, or Rainy.
Write a program randomly selecting the weather type for each of the 7 days.
Print the weather for each day
import random
weather = ['Sunny', 'Cloudy', 'Rainy']
days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
print("7-Day Weather Forecast:")
for day in days:
forecast = random.choice(weather)
print(f"{day}: {forecast}")
7-Day Weather Forecast:
Sunday: Cloudy
Monday: Sunny
Tuesday: Rainy
Wednesday: Rainy
Thursday: Rainy
Friday: Sunny
Saturday: Cloudy
Simulations
Homework Hack 1
Objective: Simulate a random coffee shop queue and determine how long it takes for customers to get served.
Task: Simulate a coffee shop with 5 customers. Each customer has a random service time (between 1 and 5 minutes). The coffee shop serves customers in the order they arrive. Calculate and print the total time it takes for all 5 customers to be served.
import random
def coffee_shop_queue():
customers = ['Claire', 'Julia', 'Hannah', 'Evie', 'Chiikawa']
random.shuffle(customers)
print("Coffee Shop Queue:\n")
total_time = 0
for customer in customers:
service_time = random.randint(1, 5)
print(f"{customer}: Service time = {service_time} minutes")
total_time += service_time
print(f"\nTotal time to serve all customers: {total_time} minutes")
coffee_shop_queue()
Coffee Shop Queue:
Claire: Service time = 3 minutes
Evie: Service time = 3 minutes
Chiikawa: Service time = 4 minutes
Julia: Service time = 1 minutes
Hannah: Service time = 3 minutes
Total time to serve all customers: 14 minutes