python

exercises

exercises.pyšŸ
"""
04 - Data Structures: Exercises
Practice with lists, tuples, dicts, and sets!
"""

print("=" * 60)
print("DATA STRUCTURES - EXERCISES")
print("=" * 60)

# =============================================================================
# EXERCISE 1: List Operations
# =============================================================================
print("\n--- Exercise 1: List Operations ---")

# Given list:
numbers = [10, 20, 30, 40, 50]

# TODO:
# a) Add 60 to the end
# b) Insert 15 at index 1
# c) Remove 30 from the list
# d) Get the sum and average of all numbers

# Your code here:
# After all operations, print the final list, sum, and average

# =============================================================================
# EXERCISE 2: List Slicing
# =============================================================================
print("\n--- Exercise 2: List Slicing ---")

# Given list:
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

# TODO: Create these slices:
first_three = None      # ['a', 'b', 'c']
last_three = None       # ['h', 'i', 'j']
middle = None           # ['d', 'e', 'f', 'g']
every_second = None     # ['a', 'c', 'e', 'g', 'i']
reversed_list = None    # ['j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']

# =============================================================================
# EXERCISE 3: Tuple Unpacking
# =============================================================================
print("\n--- Exercise 3: Tuple Unpacking ---")

# Given tuple:
person = ("John", 30, "Engineer", "New York", "USA")

# TODO: Unpack into:
# name = first element
# age = second element
# rest = remaining elements as a list

# Your code here:
name = None
age = None
rest = None

# =============================================================================
# EXERCISE 4: Dictionary Creation
# =============================================================================
print("\n--- Exercise 4: Dictionary Creation ---")

# TODO: Create a dictionary for a book with:
# - title: "Python Crash Course"
# - author: "Eric Matthes"
# - year: 2019
# - pages: 544
# - genres: ["Programming", "Technology", "Education"]

book = None

# Then add a new key "rating" with value 4.5

# =============================================================================
# EXERCISE 5: Dictionary Operations
# =============================================================================
print("\n--- Exercise 5: Dictionary Operations ---")

# Given:
inventory = {
    "apple": 50,
    "banana": 30,
    "orange": 45,
    "grape": 60
}

# TODO:
# a) Get the number of apples (safely, with default 0)
# b) Add "mango": 25 to inventory
# c) Update banana count to 35
# d) Remove grape and store its value
# e) Calculate total items in inventory

apple_count = None
grape_count = None
total_items = None

# =============================================================================
# EXERCISE 6: Set Operations
# =============================================================================
print("\n--- Exercise 6: Set Operations ---")

# Given:
python_devs = {"Alice", "Bob", "Charlie", "David"}
java_devs = {"Charlie", "David", "Eve", "Frank"}

# TODO: Find:
both_languages = None      # Developers who know both
only_python = None         # Developers who know only Python
only_java = None           # Developers who know only Java
all_devs = None            # All developers

# =============================================================================
# EXERCISE 7: Remove Duplicates
# =============================================================================
print("\n--- Exercise 7: Remove Duplicates ---")

# Given:
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]

# TODO: Remove duplicates while:
# a) Preserving order (result should be [1, 2, 3, 4, 5])
# b) Using a set (order may change)

unique_ordered = None
unique_set = None

# =============================================================================
# EXERCISE 8: Nested Dictionary
# =============================================================================
print("\n--- Exercise 8: Nested Dictionary ---")

# TODO: Create a nested dictionary for a school with:
# - Two classes: "Class A" and "Class B"
# - Each class has: teacher name and list of students
# Class A: teacher "Mr. Smith", students ["Alice", "Bob", "Charlie"]
# Class B: teacher "Ms. Johnson", students ["David", "Eve", "Frank"]

school = None

# Then: Print the teacher of Class A and the second student of Class B

# =============================================================================
# EXERCISE 9: List of Dictionaries
# =============================================================================
print("\n--- Exercise 9: List of Dictionaries ---")

# Given:
employees = [
    {"name": "Alice", "department": "Engineering", "salary": 75000},
    {"name": "Bob", "department": "Marketing", "salary": 55000},
    {"name": "Charlie", "department": "Engineering", "salary": 80000},
    {"name": "David", "department": "HR", "salary": 50000},
    {"name": "Eve", "department": "Engineering", "salary": 70000}
]

# TODO:
# a) Find all employees in Engineering department
# b) Calculate average salary
# c) Find the highest paid employee
# d) Sort employees by salary (descending)

engineering_employees = None
average_salary = None
highest_paid = None
sorted_by_salary = None

# =============================================================================
# EXERCISE 10: Word Frequency
# =============================================================================
print("\n--- Exercise 10: Word Frequency ---")

# Given text:
text = """Python is a great programming language.
Python is easy to learn. Python is used worldwide.
Programming in Python is fun."""

# TODO: Create a dictionary with word frequencies (case-insensitive)
# Hint: Convert to lowercase, split, and count

word_count = None

# Find the most common word

# =============================================================================
# EXERCISE 11: Matrix Operations
# =============================================================================
print("\n--- Exercise 11: Matrix Operations ---")

# Given matrix:
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# TODO:
# a) Calculate the sum of all elements
# b) Calculate the sum of the main diagonal (1, 5, 9)
# c) Find the maximum element
# d) Transpose the matrix (rows become columns)

total_sum = None
diagonal_sum = None
max_element = None
transposed = None

# =============================================================================
# EXERCISE 12: Grouping
# =============================================================================
print("\n--- Exercise 12: Grouping ---")

# Given:
students = [
    ("Alice", "A"),
    ("Bob", "B"),
    ("Charlie", "A"),
    ("David", "C"),
    ("Eve", "B"),
    ("Frank", "A")
]

# TODO: Group students by grade
# Result should be: {"A": ["Alice", "Charlie", "Frank"], "B": ["Bob", "Eve"], "C": ["David"]}

grouped = None

# =============================================================================
# EXERCISE 13: Data Transformation
# =============================================================================
print("\n--- Exercise 13: Data Transformation ---")

# Given:
data = [
    ("product1", 10, 5.99),
    ("product2", 20, 9.99),
    ("product3", 15, 7.49),
]

# TODO: Transform into list of dicts with keys: name, quantity, price, total
# total = quantity * price

products = None

# =============================================================================
# EXERCISE 14: Set Comprehension
# =============================================================================
print("\n--- Exercise 14: Set Comprehension ---")

# Given:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# TODO: Create sets using comprehension:
squares = None        # {1, 4, 9, 16, 25, 36, 49, 64, 81, 100}
even_cubes = None     # Cubes of even numbers only

# =============================================================================
# EXERCISE 15: Dict Comprehension Challenge
# =============================================================================
print("\n--- Exercise 15: Dict Comprehension ---")

# Given:
words = ["hello", "world", "python", "programming"]

# TODO: Create dicts using comprehension:
word_lengths = None       # {"hello": 5, "world": 5, ...}
first_last = None         # {"hello": ("h", "o"), "world": ("w", "d"), ...}
long_words = None         # Only words longer than 5 characters with their lengths

# =============================================================================
# SOLUTIONS
# =============================================================================
print("\n" + "=" * 60)
print("SOLUTIONS (scroll down after trying!)")
print("=" * 60)

"""
EXERCISE 1:
numbers.append(60)
numbers.insert(1, 15)
numbers.remove(30)
total = sum(numbers)
average = total / len(numbers)

EXERCISE 2:
first_three = letters[:3]
last_three = letters[-3:]
middle = letters[3:7]
every_second = letters[::2]
reversed_list = letters[::-1]

EXERCISE 3:
name, age, *rest = person

EXERCISE 4:
book = {
    "title": "Python Crash Course",
    "author": "Eric Matthes",
    "year": 2019,
    "pages": 544,
    "genres": ["Programming", "Technology", "Education"]
}
book["rating"] = 4.5

EXERCISE 5:
apple_count = inventory.get("apple", 0)
inventory["mango"] = 25
inventory["banana"] = 35
grape_count = inventory.pop("grape")
total_items = sum(inventory.values())

EXERCISE 6:
both_languages = python_devs & java_devs
only_python = python_devs - java_devs
only_java = java_devs - python_devs
all_devs = python_devs | java_devs

EXERCISE 7:
# Preserving order
unique_ordered = list(dict.fromkeys(numbers))
# Or:
seen = set()
unique_ordered = [x for x in numbers if not (x in seen or seen.add(x))]
# Using set (order may change)
unique_set = list(set(numbers))

EXERCISE 8:
school = {
    "Class A": {
        "teacher": "Mr. Smith",
        "students": ["Alice", "Bob", "Charlie"]
    },
    "Class B": {
        "teacher": "Ms. Johnson",
        "students": ["David", "Eve", "Frank"]
    }
}
print(school["Class A"]["teacher"])
print(school["Class B"]["students"][1])

EXERCISE 9:
engineering_employees = [e for e in employees if e["department"] == "Engineering"]
average_salary = sum(e["salary"] for e in employees) / len(employees)
highest_paid = max(employees, key=lambda x: x["salary"])
sorted_by_salary = sorted(employees, key=lambda x: x["salary"], reverse=True)

EXERCISE 10:
words = text.lower().replace(".", "").replace(",", "").split()
word_count = {}
for word in words:
    word_count[word] = word_count.get(word, 0) + 1
most_common = max(word_count, key=word_count.get)

EXERCISE 11:
total_sum = sum(sum(row) for row in matrix)
diagonal_sum = sum(matrix[i][i] for i in range(len(matrix)))
max_element = max(max(row) for row in matrix)
transposed = [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]

EXERCISE 12:
grouped = {}
for name, grade in students:
    if grade not in grouped:
        grouped[grade] = []
    grouped[grade].append(name)

EXERCISE 13:
products = [
    {"name": name, "quantity": qty, "price": price, "total": qty * price}
    for name, qty, price in data
]

EXERCISE 14:
squares = {x**2 for x in numbers}
even_cubes = {x**3 for x in numbers if x % 2 == 0}

EXERCISE 15:
word_lengths = {w: len(w) for w in words}
first_last = {w: (w[0], w[-1]) for w in words}
long_words = {w: len(w) for w in words if len(w) > 5}
"""

print("\nšŸŽ‰ Great job! Move on to 05_functions when ready!")
Exercises - Python Tutorial | DeepML