These independent exercises will train you to use advanced data structures in practical, everyday scenarios. You will progress from simple operations to complex systems:
You can write each of these exercises in a separate file. Focus on writing clean functions and testing them carefully!
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)
my_dict[key] = value. You just need an if key in my_dict: check first to print the correct message.
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.")
grid[row][col]) for this one! Just loop through the rows, and then loop through the desks in each row:forrowinoffice_grid:fordeskinrow:# check if it is "E"
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}")
in operator before trying to access the value to avoid a KeyError crash:
ifiteminmenu: total += menu[item]else:f"Sorry, '{item}' is not on the menu.")
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:
"O", change it to an "X" and print "Seat successfully booked!""X", print "Error: That seat is already taken."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)
seating_plan[row][col].
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:
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}")
ifdepartmentnot indirectory: directory[department] = []# Create the empty list first!directory[department].append(name)