Tuple Exercises
Comprehensive Exercise Set
Practice problems covering all tuple concepts:
- **Basic Operations**: Creation, access, unpacking
- **Intermediate Problems**: Nesting, conversion, methods
- **Advanced Challenges**: Memory efficiency, performance
- **Real-world Scenarios**: Practical applications
# Example solutions for basic problems
# 1. Tuple creation with mixed types
mixed = (1, "two", 3.0, False)
# 2. Unpacking with starred expression
first, *rest = (1, 2, 3, 4, 5)
# 3. Nested tuple access
matrix = ((1, 2), (3, 4))
value = matrix[1][0] # 3
# 4. Tuple concatenation
combined = (1, 2) + (3, 4) # (1, 2, 3, 4)
mixed = (1, 'two', 3.0, False) first = 1, rest = [2, 3, 4, 5] value = 3 combined = (1, 2, 3, 4)
Intermediate Challenges
Problem | Description | Solution Hint |
---|---|---|
Tuple Rotation | Rotate elements by n positions | Use slicing: t[n:] + t[:n] |
Frequency Analysis | Count all element occurrences | Combine count() with set |
Run-length Encoding | Compress consecutive duplicates | (elem, count) tuples |
Matrix Transpose | Flip rows and columns | Nested comprehension |
Tuple Zipping | Pair elements from multiple tuples | zip(t1, t2, t3) |
Advanced Problems
Complex tuple manipulation challenges:
- **Memoization Decorator**: Use tuples as cache keys
- **Vector Operations**: Implement math operations on coordinate tuples
- **Database Simulation**: Tuple-based record storage with indexing
- **Tree Structures**: Implement nested tuple trees with traversal
# Advanced example: Memoization with tuples
from functools import lru_cache
@lru_cache(maxsize=None)
def expensive_function(args_tuple):
# Simulate expensive computation
return sum(args_tuple) ** 2
# Tuples are hashable and can be cache keys
print(expensive_function((1, 2, 3)))
print(expensive_function((1, 2, 3))) # Cached result
36 36
Performance Challenges
Optimization-focused problems:
- **Large Dataset Processing**: Efficient tuple handling
- **Memory Comparison**: Tuple vs list implementations
- **Batch Operations**: Minimizing tuple creation overhead
- **Custom Sequences**: Building tuple-like classes
# Performance example: Batch processing
def process_batches(data, batch_size=1000):
for i in range(0, len(data), batch_size):
batch = tuple(data[i:i+batch_size])
# Process immutable batch
yield sum(batch)
# Simulate large dataset
big_data = range(1, 1000001)
results = list(process_batches(big_data))
print(f"Processed {len(results)} batches")
Processed 1000 batches