python

exercises

exercises.py🐍
"""
11 - Advanced Data Handling: Exercises
Practice copy, collections, and data classes.
"""

print("=" * 60)
print("ADVANCED DATA HANDLING EXERCISES")
print("=" * 60)

import copy
from collections import Counter, defaultdict, namedtuple, deque

# =============================================================================
# EXERCISE 1: Deep Copy
# Given a nested dictionary, create a deep copy and modify the copy
# without affecting the original.
# =============================================================================
print("\n--- Exercise 1: Deep Copy ---")

# Your code here:
# original = {'a': [1, 2, {'b': [3, 4]}]}
# Create deep copy and modify the innermost list


# =============================================================================
# EXERCISE 2: Counter - Character Frequency
# Given a string, find the 3 most common characters (excluding spaces).
# =============================================================================
print("\n--- Exercise 2: Character Frequency ---")

# Your code here:
# text = "abracadabra alakazam"
# Find 3 most common characters


# =============================================================================
# EXERCISE 3: defaultdict - Group by Category
# Given a list of (item, category) tuples, group items by category.
# =============================================================================
print("\n--- Exercise 3: Group by Category ---")

# Your code here:
# items = [
#     ('apple', 'fruit'), ('carrot', 'vegetable'), ('banana', 'fruit'),
#     ('broccoli', 'vegetable'), ('orange', 'fruit')
# ]
# Group into {'fruit': [...], 'vegetable': [...]}


# =============================================================================
# EXERCISE 4: namedtuple - Book Catalog
# Create a Book namedtuple with title, author, year, isbn.
# Create 3 books and sort them by year.
# =============================================================================
print("\n--- Exercise 4: Book Catalog ---")

# Your code here:


# =============================================================================
# EXERCISE 5: deque - Sliding Window Maximum
# Given a list and window size k, find the maximum in each sliding window.
# Use deque for efficient solution.
# =============================================================================
print("\n--- Exercise 5: Sliding Window Maximum ---")

# Your code here:
# nums = [1, 3, -1, -3, 5, 3, 6, 7]
# k = 3
# Expected: [3, 3, 5, 5, 6, 7]


# =============================================================================
# EXERCISE 6: Counter - Anagram Check
# Write a function to check if two strings are anagrams using Counter.
# =============================================================================
print("\n--- Exercise 6: Anagram Check ---")

# Your code here:


# Test:
# print(is_anagram("listen", "silent"))  # True
# print(is_anagram("hello", "world"))    # False


# =============================================================================
# EXERCISE 7: defaultdict - Word Index
# Create a word index showing which lines each word appears in.
# =============================================================================
print("\n--- Exercise 7: Word Index ---")

# Your code here:
# lines = [
#     "hello world",
#     "world is big",
#     "hello again"
# ]
# Expected: {'hello': [0, 2], 'world': [0, 1], ...}


# =============================================================================
# EXERCISE 8: Data Class - Inventory
# Create an Inventory dataclass for products with:
# - name, quantity, price
# - Methods: total_value(), is_low_stock(threshold)
# =============================================================================
print("\n--- Exercise 8: Inventory Data Class ---")

from dataclasses import dataclass

# Your code here:


# =============================================================================
# EXERCISE 9: deque - Recent Items Cache
# Implement a RecentItems class that keeps track of the N most recently
# added items using deque.
# =============================================================================
print("\n--- Exercise 9: Recent Items Cache ---")

# Your code here:


# Test:
# cache = RecentItems(3)
# cache.add("a")
# cache.add("b")
# cache.add("c")
# cache.add("d")  # "a" should be removed
# print(cache.get_all())  # ['b', 'c', 'd']


# =============================================================================
# EXERCISE 10: Counter - Text Statistics
# Analyze text and return statistics: word count, unique words,
# most common words, average word length.
# =============================================================================
print("\n--- Exercise 10: Text Statistics ---")

# Your code here:


# Test:
# text = "Python is great Python is easy to learn"
# stats = analyze_text(text)
# print(stats)


# =============================================================================
# SOLUTIONS
# =============================================================================
print("\n\n" + "=" * 60)
print("SOLUTIONS")
print("=" * 60)

# SOLUTION 1
print("\n--- Solution 1: Deep Copy ---")

original = {'a': [1, 2, {'b': [3, 4]}]}
deep_copied = copy.deepcopy(original)
deep_copied['a'][2]['b'][0] = 999

print(f"Original: {original}")
print(f"Deep copy: {deep_copied}")
print("Original unchanged!")

# SOLUTION 2
print("\n--- Solution 2: Character Frequency ---")

text = "abracadabra alakazam"
char_count = Counter(text.replace(" ", ""))
print(f"3 most common: {char_count.most_common(3)}")

# SOLUTION 3
print("\n--- Solution 3: Group by Category ---")

items = [
    ('apple', 'fruit'), ('carrot', 'vegetable'), ('banana', 'fruit'),
    ('broccoli', 'vegetable'), ('orange', 'fruit')
]

grouped = defaultdict(list)
for item, category in items:
    grouped[category].append(item)

print(f"Grouped: {dict(grouped)}")

# SOLUTION 4
print("\n--- Solution 4: Book Catalog ---")

Book = namedtuple('Book', 'title author year isbn')

books = [
    Book("1984", "George Orwell", 1949, "123"),
    Book("Python Crash Course", "Eric Matthes", 2015, "456"),
    Book("Clean Code", "Robert Martin", 2008, "789"),
]

sorted_books = sorted(books, key=lambda b: b.year)
print("Books sorted by year:")
for book in sorted_books:
    print(f"  {book.year}: {book.title} by {book.author}")

# SOLUTION 5
print("\n--- Solution 5: Sliding Window Maximum ---")

def sliding_max(nums, k):
    if not nums:
        return []
    
    result = []
    dq = deque()
    
    for i, num in enumerate(nums):
        # Remove elements outside window
        while dq and dq[0] < i - k + 1:
            dq.popleft()
        
        # Remove smaller elements
        while dq and nums[dq[-1]] < num:
            dq.pop()
        
        dq.append(i)
        
        # Add to result when window is full
        if i >= k - 1:
            result.append(nums[dq[0]])
    
    return result

nums = [1, 3, -1, -3, 5, 3, 6, 7]
k = 3
print(f"Sliding max (k={k}): {sliding_max(nums, k)}")

# SOLUTION 6
print("\n--- Solution 6: Anagram Check ---")

def is_anagram(s1, s2):
    return Counter(s1.lower().replace(" ", "")) == Counter(s2.lower().replace(" ", ""))

print(f"'listen' and 'silent': {is_anagram('listen', 'silent')}")
print(f"'hello' and 'world': {is_anagram('hello', 'world')}")

# SOLUTION 7
print("\n--- Solution 7: Word Index ---")

lines = [
    "hello world",
    "world is big",
    "hello again"
]

word_index = defaultdict(list)
for line_num, line in enumerate(lines):
    for word in line.split():
        if line_num not in word_index[word]:
            word_index[word].append(line_num)

print("Word index:")
for word, indices in sorted(word_index.items()):
    print(f"  '{word}': {indices}")

# SOLUTION 8
print("\n--- Solution 8: Inventory Data Class ---")

@dataclass
class Product:
    name: str
    quantity: int
    price: float
    
    def total_value(self):
        return self.quantity * self.price
    
    def is_low_stock(self, threshold=10):
        return self.quantity < threshold

laptop = Product("Laptop", 5, 999.99)
keyboard = Product("Keyboard", 50, 29.99)

print(f"Laptop total value: ${laptop.total_value():.2f}")
print(f"Laptop low stock? {laptop.is_low_stock()}")
print(f"Keyboard low stock? {keyboard.is_low_stock()}")

# SOLUTION 9
print("\n--- Solution 9: Recent Items Cache ---")

class RecentItems:
    def __init__(self, max_size):
        self.items = deque(maxlen=max_size)
    
    def add(self, item):
        self.items.append(item)
    
    def get_all(self):
        return list(self.items)

cache = RecentItems(3)
cache.add("a")
cache.add("b")
cache.add("c")
cache.add("d")
print(f"Recent items: {cache.get_all()}")

# SOLUTION 10
print("\n--- Solution 10: Text Statistics ---")

def analyze_text(text):
    words = text.lower().split()
    word_count = Counter(words)
    
    return {
        'total_words': len(words),
        'unique_words': len(set(words)),
        'most_common': word_count.most_common(3),
        'avg_word_length': sum(len(w) for w in words) / len(words)
    }

text = "Python is great Python is easy to learn"
stats = analyze_text(text)
print("Text statistics:")
for key, value in stats.items():
    print(f"  {key}: {value}")

print("\n" + "=" * 60)
print("END OF EXERCISES")
print("=" * 60)
Exercises - Python Tutorial | DeepML