Homework Problem 1

def calculate_median(numbers):
    # Check if the input list is empty
    if len(numbers) == 0:
        raise ValueError("Input list is empty")

    # Sort the list of numbers in ascending order
    numbers.sort()

    # Calculate the index of the middle element(s)
    middle_index = len(numbers) // 2

    # Check if the list has an odd number of elements
    if len(numbers) % 2 == 1:
        # If odd, return the middle element
        median = numbers[middle_index]
    else:
        # If even, calculate the average of the two middle elements
        median = (numbers[middle_index - 1] + numbers[middle_index]) / 2

    return median

# Example usage:
numbers = [5, 2, 9, 1, 5, 6]
result = calculate_median(numbers)
print(f"The median of {numbers} is {result}")

The median of [1, 2, 5, 5, 6, 9] is 5.0

Homework Problem 2

import random

def guess_the_number():
    # Generate a random number between 1 and 100
    secret_number = random.randint(1, 100)
    
    # Set the number of allowed attempts
    max_attempts = 5
    attempts = 0
    
    print("Welcome to the Guess the Number Game!")
    print(f"Try to guess the secret number between 1 and 100. You have {max_attempts} attempts.")

    while attempts < max_attempts:
        try:
            # Get the player's guess
            guess = int(input("Enter your guess: "))
            
            # Check if the guess is correct
            if guess == secret_number:
                print("Congratulations! You've guessed the correct number.")
                break
            elif guess < secret_number:
                print("Too low! Try a higher number.")
            else:
                print("Too high! Try a lower number.")
            
            # Increment the number of attempts
            attempts += 1
            remaining_attempts = max_attempts - attempts
            print(f"You have {remaining_attempts} attempts left.")
        
        except ValueError:
            print("Invalid input. Please enter a valid number.")

    else:
        print(f"Sorry, you've run out of attempts. The secret number was {secret_number}.")

guess_the_number()

Welcome to the Guess the Number Game!
Try to guess the secret number between 1 and 100. You have 5 attempts.
Too high! Try a lower number.
You have 4 attempts left.
Too low! Try a higher number.
You have 3 attempts left.
Too high! Try a lower number.
You have 2 attempts left.
Too low! Try a higher number.
You have 1 attempts left.
Too low! Try a higher number.
You have 0 attempts left.
Sorry, you've run out of attempts. The secret number was 39.