Popcorn Hack #1
Question: Name two real-world applications where random number generation is essential and briefly explain why.
Answer:
-
Cryptography Random numbers are used to generate encryption keys, which keep data secure during communication (like HTTPS websites, encrypted messages, or banking apps). If these keys weren’t random, hackers could easily predict them and break into systems.
-
Simulations (Weather Forecasting or Risk Analysis) Random numbers help model uncertainty in complex systems. For example, in weather forecasting, simulations run thousands of scenarios with slight variations (powered by random numbers) to predict likely outcomes. Similarly, in finance or engineering, Monte Carlo simulations use random numbers to estimate risk or performance under uncertain conditions.
Popcorn Hack #2
import random
def magic_8_ball():
return random.choices(["Yes", "No", "Maybe"], weights=[50, 25, 25])[0]
# Test your function
for i in range(10):
print(f"Magic 8-Ball says: {magic_8_ball()}")
Magic 8-Ball says: No
Magic 8-Ball says: No
Magic 8-Ball says: No
Magic 8-Ball says: Maybe
Magic 8-Ball says: Yes
Magic 8-Ball says: No
Magic 8-Ball says: Maybe
Magic 8-Ball says: Maybe
Magic 8-Ball says: Yes
Magic 8-Ball says: No
Popcorn Hack #3
# Updated traffic light simulation
states = ["Green", "Yellow", "Red"]
durations = {"Green": 5, "Yellow": 2, "Red": 4}
timeline = []
# Simulate 20 time steps
time = 0
state = "Green"
counter = 0
while time < 20:
timeline.append((time, state))
counter += 1
if counter == durations[state]:
counter = 0
current_index = states.index(state)
state = states[(current_index + 1) % len(states)]
time += 1
for t, s in timeline:
print(f"Time {t}: {s}")
Time 0: Green
Time 1: Green
Time 2: Green
Time 3: Green
Time 4: Green
Time 5: Yellow
Time 6: Yellow
Time 7: Red
Time 8: Red
Time 9: Red
Time 10: Red
Time 11: Green
Time 12: Green
Time 13: Green
Time 14: Green
Time 15: Green
Time 16: Yellow
Time 17: Yellow
Time 18: Red
Time 19: Red
How is this a simulation? What is it’s real world impact?
Answer: This is a simulation because it models the behavior of a real-world traffic light system over time, using defined rules and durations. Its real-world impact lies in helping city planners and engineers test traffic patterns, optimize flow, and improve safety at intersections.
Homework Hack #1:
import random
def roll_dice():
"""Roll two dice and return their values and sum."""
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
total = die1 + die2
print(f"You rolled {die1} + {die2} = {total}")
return total
def play_dice_game():
"""
Play one round of the dice game.
Returns True if player wins, False if player loses.
"""
first_roll = roll_dice()
if first_roll in (7, 11):
print("You win!")
return True
elif first_roll in (2, 3, 12):
print("Craps! You lose!")
return False
else:
point = first_roll
print(f"Point is set to {point}. Roll again until you roll {point} (win) or 7 (lose).")
while True:
roll = roll_dice()
if roll == point:
print("You rolled the point again. You win!")
return True
elif roll == 7:
print("You rolled a 7. You lose!")
return False
def main():
"""Main game function with game loop and statistics."""
wins = 0
losses = 0
while True:
choice = input("\nDo you want to play a round? (y/n): ").strip().lower()
if choice == 'y':
result = play_dice_game()
if result:
wins += 1
else:
losses += 1
print(f"Current Stats -> Wins: {wins}, Losses: {losses}")
elif choice == 'n':
print(f"\nFinal Stats -> Wins: {wins}, Losses: {losses}")
print("Thanks for playing!")
break
else:
print("Please enter 'y' or 'n'.")
if __name__ == "__main__":
print("Welcome to the Dice Game!")
main()
Welcome to the Dice Game!
Please enter 'y' or 'n'.
You rolled 5 + 5 = 10
Point is set to 10. Roll again until you roll 10 (win) or 7 (lose).
You rolled 2 + 6 = 8
You rolled 3 + 4 = 7
You rolled a 7. You lose!
Current Stats -> Wins: 0, Losses: 1
You rolled 4 + 3 = 7
You win!
Current Stats -> Wins: 1, Losses: 1
---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
Cell In[3], line 60
58 if __name__ == "__main__":
59 print("Welcome to the Dice Game!")
---> 60 main()
Cell In[3], line 43, in main()
40 losses = 0
42 while True:
---> 43 choice = input("\nDo you want to play a round? (y/n): ").strip().lower()
44 if choice == 'y':
45 result = play_dice_game()
File ~/nighthawk/avika_2025/venv/lib/python3.12/site-packages/ipykernel/kernelbase.py:1282, in Kernel.raw_input(self, prompt)
1280 msg = "raw_input was called, but this frontend does not support input requests."
1281 raise StdinNotImplementedError(msg)
-> 1282 return self._input_request(
1283 str(prompt),
1284 self._parent_ident["shell"],
1285 self.get_parent("shell"),
1286 password=False,
1287 )
File ~/nighthawk/avika_2025/venv/lib/python3.12/site-packages/ipykernel/kernelbase.py:1325, in Kernel._input_request(self, prompt, ident, parent, password)
1322 except KeyboardInterrupt:
1323 # re-raise KeyboardInterrupt, to truncate traceback
1324 msg = "Interrupted by user"
-> 1325 raise KeyboardInterrupt(msg) from None
1326 except Exception:
1327 self.log.warning("Invalid Message:", exc_info=True)
KeyboardInterrupt: Interrupted by user