Data Management Exercises

Skills Challenge: Real-World Applications

These independent exercises will train you to use advanced data structures in practical, everyday scenarios. You will progress from simple operations to complex systems:

  • Basic Dictionaries: Adding and modifying simple key-value data.
  • Basic Matrices: Traversing 2D spaces to extract information.
  • Advanced Dictionaries & Lists: Lookups, coordinate management, and combining structures safely!

You can write each of these exercises in a separate file. Focus on writing clean functions and testing them carefully!

Exercise 1: The Contact Book
Points: 0/1

Let's start by managing a simple digital contact book using a dictionary. The keys will be people's names, and the values will be their phone numbers.

Write a function update_contact(contacts: dict, name: str, phone: str).

If the person is already in the dictionary, the function should update their number and print a message saying it was updated. If they are not in the dictionary yet, it should add them and print that they were added.

Example usage:

phone_book = {
    "Alice": "555-1234"
}

update_contact(phone_book, "Alice", "555-9999")
update_contact(phone_book, "Bob", "555-0000")

print(phone_book)
Expected Output
Updated Alice's number. Added Bob to contacts. {'Alice': '555-9999', 'Bob': '555-0000'}
In a dictionary, the syntax to add a new key and the syntax to update an existing key is exactly the same! my_dict[key] = value. You just need an if key in my_dict: check first to print the correct message.
Exercise 2: The Office Desk Counter
Points: 0/1

Now let's practice working with nested lists (a 2D Matrix). A startup company has mapped out their office floor plan as a list of lists. Desks that are available are marked with an "E" (Empty), and desks currently used by someone are marked with an "O" (Occupied).

Write a function count_empty_desks(office_grid: list).

The function should traverse the entire grid, count how many "E" strings there are in total, and return that number as an integer.

Example usage:

floor_plan = [
    ["O", "E", "O", "O"],
    ["E", "E", "O", "E"],
    ["O", "O", "O", "O"]
]

available = count_empty_desks(floor_plan)
print(f"There are {available} empty desks remaining.")
Expected Output
There are 4 empty desks remaining.
You don't need coordinates (like grid[row][col]) for this one! Just loop through the rows, and then loop through the desks in each row:
for row in office_grid:
    for desk in row:
        # check if it is "E"
Exercise 3: The Café Cashier
Points: 0/2

Let's step it up. You are programming the cash register for a local café. The prices are stored in a dictionary, but customers sometimes try to order items that aren't on the menu!

Write a function named calculate_total(menu: dict, order: list).

The function should loop through the order list. If the requested item is found in the menu, add its price to a running total. If the item is not in the menu, print an error message stating that the item is unavailable.

Finally, the function must return the final total amount as a float.

Example usage:

cafe_menu = {
    "Coffee": 3.50,
    "Tea": 2.50,
    "Croissant": 4.00,
    "Sandwich": 6.50
}

customer_order = ["Coffee", "Pancakes", "Tea", "Coffee"]
total = calculate_total(cafe_menu, customer_order)
print(f"\nTotal to pay: ${total}")
Expected Output
Sorry, 'Pancakes' is not on the menu. Total to pay: $9.5
Remember to use the in operator before trying to access the value to avoid a KeyError crash:
if item in menu:
    total += menu[item]
else:
    print(f"Sorry, '{item}' is not on the menu.")
Exercise 4: Cinema Seating Plan
Points: 0/2

Let's revisit 2D lists, but this time we need to modify specific locations. You are managing reservations for a small cinema. An empty seat is represented by "O" and a booked seat is represented by "X".

Write a function book_seat(seating_plan: list, row: int, col: int).

The function must check the provided row and column coordinates:

  • If the seat is an "O", change it to an "X" and print "Seat successfully booked!"
  • If the seat is already an "X", print "Error: That seat is already taken."
  • Optional Bonus: If the row or column numbers are outside the boundaries of the list, print "Error: Invalid seat coordinates."

Example usage:

cinema = [
    ["O", "O", "X", "O"],
    ["O", "O", "O", "O"],
    ["X", "X", "O", "X"]
]

print("--- Attempt 1 ---")
book_seat(cinema, 1, 2) # Row 1, Col 2

print("--- Attempt 2 ---")
book_seat(cinema, 0, 2) # Row 0, Col 2

print("\nFinal Seating Plan:")
for row in cinema:
    print(row)
Expected Output
--- Attempt 1 --- Seat successfully booked! --- Attempt 2 --- Error: That seat is already taken. Final Seating Plan: ['O', 'O', 'X', 'O'] ['O', 'O', 'X', 'O'] ['X', 'X', 'O', 'X']
Unlike Exercise 2, you must access the specific spot directly. Always use the row first, then the column: seating_plan[row][col].
Exercise 5: The Employee Directory
Points: 0/3

This is a classic Part 5 problem: Combining Dictionaries and Lists. You need to organize employees into a dictionary where the keys are Department names, and the values are Lists of employee names.

Write a function add_employee(directory: dict, department: str, name: str).

When adding a new employee:

  1. If the department doesn't exist in the dictionary yet, you must first create it and assign an empty list to it.
  2. Then, append the employee's name to that department's list.

Example usage:

company = {}

# Adding employees
add_employee(company, "Sales", "Alice")
add_employee(company, "IT", "Bob")
add_employee(company, "Sales", "Charlie")
add_employee(company, "HR", "David")
add_employee(company, "IT", "Eve")

print("Company Directory:")
for dept, employees in company.items():
    print(f"\n{dept} Department:")
    for emp in employees:
        print(f" - {emp}")
Expected Output
Company Directory: Sales Department: - Alice - Charlie IT Department: - Bob - Eve HR Department: - David
Inside your function, do this before appending:
if department not in directory:
    directory[department] = [] # Create the empty list first!
    
directory[department].append(name)