Magic 8-Ball says: Yes
Magic 8-Ball says: No
Magic 8-Ball says: Yes
Magic 8-Ball says: Yes
Magic 8-Ball says: Ask again later
Magic 8-Ball says: No
Magic 8-Ball says: Yes
Magic 8-Ball says: No
Magic 8-Ball says: Yes
Magic 8-Ball says: Ask again later
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
### 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("You lose!")
return False
else:
point = first_roll
print(f"Point is set to {point}. Keep rolling until you roll {point} again (win) or a 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:
play = input("\nDo you want to play a round? (yes/no): ").strip().lower()
if play in ['yes', 'y']:
result = play_dice_game()
if result:
wins += 1
else:
losses += 1
elif play in ['no', 'n']:
print(f"\nFinal Statistics:\nWins: {wins}\nLosses: {losses}")
break
else:
print("Please enter 'yes' or 'no'.")
if __name__ == "__main__":
print("Welcome to the Dice Game!")
main()
import time
import random
# Generate a large sorted list
data_size = 20000000
sorted_data = sorted(random.sample(range(100000000), data_size))
# Target to find (worst case for linear search)
target = sorted_data[-1] # Last element
# O(n) - Linear Search
def linear_search(arr, target):
for i, element in enumerate(arr):
if element == target:
return i
return -1
# O(log n) - Binary Search
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
# Compare performance
print("Testing with data size:", data_size)
start = time.time()
linear_result = linear_search(sorted_data, target)
linear_time = time.time() - start
print(f"Linear search: {linear_time:.6f} seconds")
start = time.time()
binary_result = binary_search(sorted_data, target)
binary_time = time.time() - start
print(f"Binary search: {binary_time:.6f} seconds")
print(f"Binary search is approximately {linear_time/binary_time:.0f}x faster")
Testing with data size: 20000000
Linear search: 0.700474 seconds
Binary search: 0.000023 seconds
Binary search is approximately 30604x faster