Solutions – OOP and Algorithm Exercises¶
These reference solutions correspond to the practice tasks from Lesson 04 – OOP and Algorithm Basics. They illustrate one possible approach to implementing the sample classes and algorithms discussed in the lesson.
1. Dog Class¶
class Dog:
"""Simple dog with a name and a trick."""
def __init__(self, name: str) -> None:
self.name = name
def bark(self) -> str:
"""Return a bark sound."""
return "woof"
def fetch(self, item: str) -> str:
"""Return a message that the dog fetched an item."""
return f"{self.name} fetched {item}!"
fetch() method beyond the bark() method from the lesson.
2. Student Grades¶
alice = Student("Alice")
for score in [90, 95, 88]:
alice.add_grade(score)
print(alice.average()) # 91.0
Student object, record three grades, and print the average using the class's average() method.
3. Bubble Sort and Binary Search¶
def bubble_sort(nums: list[int]) -> None:
"""Sort a list of numbers in place using Bubble Sort."""
n = len(nums)
for i in range(n):
for j in range(0, n - i - 1):
if nums[j] > nums[j + 1]:
nums[j], nums[j + 1] = nums[j + 1], nums[j]
def binary_search(items: list[int], target: int) -> int:
"""Return the index of target or -1 if not found."""
low, high = 0, len(items) - 1
while low <= high:
mid = (low + high) // 2
if items[mid] == target:
return mid
if items[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
nums = [5, 3, 1, 4, 2]
bubble_sort(nums)
print(nums) # [1, 2, 3, 4, 5]
print(binary_search(nums, 4)) # 3
4. Merge Sort Efficiency¶
Merge Sort splits the input in half at each step and merges the results, leading to a typical complexity of O(n log n). Bubble Sort repeatedly scans the list and swaps items, producing O(n^2) behavior. For large datasets this difference in growth rate makes Merge Sort significantly faster.