← Computer Programming I

Problem 1: The Exam Countdown Timer

Problem Statement: You are writing a simple utility program to help students track how much time they have left before their final exam.

Write a program that:

  1. Imports the datetime module (you may alias it as dt if you wish).
  2. Asks the user to input the year, month, and day of their exam separately.
  3. Creates a date object for the exam date using the user’s input.
  4. Gets the current date from the computer’s system.
  5. Calculates the difference between the exam date and the current date.
  6. Checks if the exam date has already passed.
    • If the exam is in the future, print: "You have X days left to study!"
    • If the exam is today, print: "Good luck! The exam is today."
    • If the exam is in the past, print: "The exam was X days ago."

Input/Output Examples:

Case 1: Exam is in the future (Assume today is 2025-12-23)

Enter exam year: 2026
Enter exam month: 1
Enter exam day: 15
You have 23 days left to study!

Case 2: Exam is in the past (Assume today is 2025-12-23)

Enter exam year: 2025
Enter exam month: 12
Enter exam day: 1
The exam was 22 days ago.

Problem 2: Where is the Space Station?

Problem Statement: The International Space Station (ISS) is constantly orbiting the Earth. There is a free, public API that provides its current coordinates in real-time.

API URL: http://api.open-notify.org/iss-now.json

Write a program that:

  1. Connects to the API using the requests library.
  2. Checks if the connection was successful (Status Code 200).
  3. If successful, converts the response text into a Python dictionary.
  4. Extracts the latitude and longitude from the nested dictionary.
  5. Prints the location clearly.

Structure of the JSON data returned by the API:

{
  "message": "success", 
  "timestamp": 1699982000, 
  "iss_position": {
    "latitude": "-25.1234", 
    "longitude": "120.5678"
  }
}

Expected Output:

Connecting to ISS satellite...
Connection Successful!
Current Location:
Latitude: -25.1234
Longitude: 120.5678

Problem 3: The Monte Carlo Dice Simulation

Problem Statement: A “Monte Carlo Simulation” is a technique used to predict the probability of different outcomes by running a simulation many times.

You are going to simulate rolling two 6-sided dice 1,000 times to analyze the distribution of the results.

Write a program that:

  1. Imports random and statistics.
  2. Creates an empty list called results.
  3. Runs a loop 1,000 times. In each iteration:
    • Simulate rolling two dice (generate two random integers between 1 and 6).
    • Calculate the sum of the two dice (result will be between 2 and 12).
    • Append this sum to the results list.
  4. After the loop finishes, use the statistics module to calculate:
    • The Mean (average) of the results.
    • The Median (middle value) of the results.
    • The Mode (most common value) of the results.
  5. Print the statistics formatted to 2 decimal places.

Hint: The statistics module has functions named mean(), median(), and mode() that take a list of numbers as an argument.

Expected Output: (Note: Numbers will vary slightly every time you run it, but should be close to these mathematical probabilities)

--- Simulation Results (1000 rolls) ---
Mean: 7.02
Median: 7.0
Mode: 7

Problem 4: Global University Search

Problem Statement: You are building a search tool for high school students looking for universities abroad. You will use the free “Hipolabs Universities API”.

API URL: http://universities.hipolabs.com/search

Write a program that:

  1. Asks the user to input a Country Name (e.g., “Turkey”, “Uzbekistan”, “United Kingdom”).
  2. Creates a parameters dictionary to pass to the API (the API expects a query parameter named country).
  3. Makes a GET request to the API.
  4. Parses the JSON response.
    • Note: This API returns a List of dictionaries, not a single dictionary.
  5. Analyzes the data:
    • If no universities are found (empty list), print "No universities found for [Country]."
    • If found, print the Total Count of universities found.
    • Print the names of the first 5 universities in the list.

Input/Output Examples:

Case 1: User enters “Uzbekistan”

Enter a country to search: Uzbekistan
Found 23 universities in Uzbekistan.
Here are the first 5:
1. Tashkent State Agrarian University
2. Ferghana Politechnical Institute
3. International Business School Kelajak ILMI
4. Management Development Institute of Singapore, Tashkent
5. Nukus State Teachers Training Institute

Case 2: User enters “Atlantis” (Non-existent)

Enter a country to search: Atlantis
No universities found for Atlantis.

Problem 5: The Tournament Scheduler

Problem Statement: You are organizing a Round-Robin E-Sports tournament. In this format, every team must play against every other team exactly once.

Writing nested loops to find these unique pairs without duplicates (e.g., A vs B is the same as B vs A) can be tricky. Fortunately, Python’s Standard Library has a module called itertools that solves this math problem for you.

Write a program that:

  1. Imports itertools and random.
  2. Defines a list of 6 team names (e.g., “Tigers”, “Dragons”, “Eagles”, “Sharks”, “Wolves”, “Bears”).
  3. Uses random.shuffle() to mix up the list order so the schedule is different every time.
  4. Uses the itertools.combinations(iterable, r) function to generate all possible unique matchups.
    • Hint: The first argument is your list of teams. The second argument r is the size of the group (2, because it’s a 1vs1 match).
  5. Iterates through these combinations and prints a numbered schedule.
  6. Prints the total number of matches calculated.

Expected Output:

--- Tournament Schedule ---
Match 1: Dragons vs Wolves
Match 2: Dragons vs Tigers
Match 3: Dragons vs Bears
...
Match 14: Tigers vs Sharks
Match 15: Eagles vs Sharks
---------------------------
Total Matches to play: 15

Problem 6: The Random User Database Builder

Problem Statement: You are testing a database and need to generate fake user data. Instead of typing it manually, you will use the “Random User Generator” API to fetch profiles and save them to a file.

API URL: https://randomuser.me/api/?results=10&nat=us (This fetches 10 random users from the US).

Write a program that:

  1. Makes a GET request to the API.
  2. Parses the JSON response.
    • Note: The user data is inside a key called "results", which is a list.
    • Challenge: The name is nested (e.g., user['name']['first']).
  3. Extracts the following fields for each user: First Name, Last Name, Email, City.
  4. Uses the csv module to write this data into a new file called fake_users.csv.
  5. Includes a header row in the CSV: first_name,last_name,email,city.

JSON Structure Hint:

{
  "results": [
    {
      "name": { "first": "brad", "last": "gibson" },
      "email": "brad.gibson@example.com",
      "location": { "city": "kilcoole", ... }
    }
  ]
}

Expected Output (Console):

Fetching data from API...
Successfully fetched 10 users.
Writing to fake_users.csv...
Done!

Expected Output (File: fake_users.csv):

first_name,last_name,email,city
brad,gibson,brad.gibson@example.com,kilcoole
alice,smith,alice.smith@example.com,austin
...

Problem 7: The "Open Library" Analyzer

Problem Statement: You are building a tool for a librarian to analyze search results from the Open Library. You want to search for a specific subject and find the thickest book (highest page count) and the oldest book (earliest publication year) from the results.

API URL: https://openlibrary.org/search.json

Critical Requirement: By default, this API returns too much data. To get the specific fields we need, you must add a parameter called fields to your request with the value: title,author_name,first_publish_year,number_of_pages_median.

Write a program that:

  1. Asks the user for a Search Subject (e.g., “Python”, “Robotics”).
  2. Sends a GET request to the API with three parameters:
    • q: The subject the user entered.
    • limit: 10 (to keep the data manageable).
    • fields: title,author_name,first_publish_year,number_of_pages_median (This is required to get the page counts!).
  3. Parses the JSON response. The list of books is under the key "docs".
  4. Loops through the books to find:
    • The book with the maximum number_of_pages_median.
    • The book with the minimum first_publish_year.
  5. Challenge: Real-world data is messy!
    • Some books do not have the number_of_pages_median key.
    • Some books do not have the first_publish_year key.
    • Your code must strictly ignore books that are missing this data to avoid crashing.
  6. Prints the title and relevant statistic for the winner in each category.

Expected Output:

Enter a subject: Artificial Intelligence
Fetching top 10 results...

--- Analysis Results ---
Thickest Book:
Title: Artificial intelligence
Pages: 1144

Oldest Book:
Title: Artificial intelligence
Year: 1977

Problem 8: The International Expense Report

Problem Statement: You have returned from a business trip with receipts in different currencies (Euros, Pounds, Yen). You need to generate a final expense report in USD.

Part 1: The Setup Create a file named expenses.csv in your project folder with the following content (including the header):

Item,Amount,Currency
Taxi,50,EUR
Lunch,2500,JPY
Hotel,120,GBP
Coffee,5,EUR
Gift,30,USD

Part 2: The Program API URL: https://open.er-api.com/v6/latest/USD (This is a free, open API that returns exchange rates relative to USD).

Write a program that:

  1. Fetches current exchange rates from the API.
  2. Creates a Lookup Dictionary from the API response (e.g., {'EUR': 0.92, 'JPY': 145.5, ...}). Note: The API gives the rate of 1 USD in other currencies. To convert TO USD, you usually divide by the rate.
  3. Reads your expenses.csv file using the csv module.
  4. For each row in the CSV:
    • Get the Amount and Currency.
    • Find the correct exchange rate in your lookup dictionary.
    • Convert the amount to USD.
  5. Calculates the Grand Total in USD.
  6. Writes a new file named expense_report.txt containing the converted list and the total.

Logic Hint for Conversion: If the API says USD -> EUR is 0.92:

  • To convert 50 EUR to USD: 50 / 0.92 = $54.34
  • Make sure to handle the case where the currency is already USD!

Expected Output (Console):

Fetching exchange rates...
Processing expenses.csv...
Report written to expense_report.txt
Total Expenses: $270.84

Expected Output (File: expense_report.txt):

Item: Taxi | Original: 50.0 EUR | USD: $58.58
Item: Lunch | Original: 2500.0 JPY | USD: $15.90
Item: Hotel | Original: 120.0 GBP | USD: $160.49
Item: Coffee | Original: 5.0 EUR | USD: $5.86
Item: Gift | Original: 30.0 USD | USD: $30.00
--------------------------------------------------
GRAND TOTAL: $270.84