MEDIUM ENUMERATE EXAMPLES
Python
#!/usr/bin/env python3
"""
MEDIUM ENUMERATE EXAMPLES
Practical applications and common patterns
"""
print("=" * 60)
print("MEDIUM ENUMERATE - Practical Use Cases")
print("=" * 60)
# Example 1: Modifying list elements by index
print("\n1. Modifying List Items Based on Position")
print("-" * 40)
scores = [85, 92, 78, 95, 88]
print(f"Original scores: {scores}")
# Add bonus points to every other score
for index, score in enumerate(scores):
if index % 2 == 0: # Even positions (0, 2, 4...)
scores[index] = score + 5
print(f" Position {index}: {score} -> {scores[index]} (bonus applied)")
else:
print(f" Position {index}: {score} (no change)")
print(f"Updated scores: {scores}")
# Example 2: Processing with previous/next context
print("\n2. Comparing Current Item with Neighbors")
print("-" * 40)
temperatures = [72, 75, 73, 80, 78, 85, 82]
print(f"Daily temperatures: {temperatures}")
for index, temp in enumerate(temperatures):
if index == 0:
print(f"Day {index + 1}: {temp}°F (first day)")
elif index == len(temperatures) - 1:
print(f"Day {index + 1}: {temp}°F (last day)")
else:
prev_temp = temperatures[index - 1]
change = temp - prev_temp
trend = "up" if change > 0 else "down" if change < 0 else "stable"
print(f"Day {index + 1}: {temp}°F ({trend} {abs(change)}° from yesterday)")
# Example 3: Building formatted output with line numbers
print("\n3. Adding Line Numbers to Text")
print("-" * 40)
code_lines = [
"def hello():",
" print('Hello, World!')",
" return True",
"",
"hello()"
]
print("Code with line numbers:")
for line_num, code in enumerate(code_lines, start=1):
if code.strip(): # Non-empty lines
print(f"{line_num:3d} | {code}")
else: # Empty lines
print(f"{line_num:3d} |")
# Example 4: Creating index mapping
print("\n4. Building Lookup Dictionary (Value to Index)")
print("-" * 40)
usernames = ["alice", "bob", "charlie", "diana", "eve"]
print(f"Usernames: {usernames}")
# Create reverse mapping: username -> position
user_positions = {user: idx for idx, user in enumerate(usernames)}
print(f"Position lookup: {user_positions}")
search_user = "charlie"
print(f"\nSearching for '{search_user}':")
print(f" Found at position: {user_positions[search_user]}")
# Example 5: Grouping items by position
print("\n5. Splitting List into Groups by Position")
print("-" * 40)
items = ["A", "B", "C", "D", "E", "F", "G", "H"]
even_items = []
odd_items = []
for index, item in enumerate(items):
if index % 2 == 0:
even_items.append(item)
else:
odd_items.append(item)
print(f"Original: {items}")
print(f"Even positions (0,2,4...): {even_items}")
print(f"Odd positions (1,3,5...): {odd_items}")
# Example 6: Progress tracking with enumerate
print("\n6. Processing with Progress Indication")
print("-" * 40)
files = ["file1.txt", "file2.txt", "file3.txt", "file4.txt", "file5.txt"]
total = len(files)
for index, filename in enumerate(files, start=1):
percentage = (index / total) * 100
print(f"[{percentage:5.1f}%] Processing {filename} ({index}/{total})")
# Example 7: Finding all occurrences with positions
print("\n7. Finding All Positions of Matching Items")
print("-" * 40)
data = [10, 25, 10, 30, 10, 45, 25, 10]
target = 10
positions = [idx for idx, value in enumerate(data) if value == target]
print(f"Data: {data}")
print(f"Looking for: {target}")
print(f"Found at positions: {positions}")
print(f"Total occurrences: {len(positions)}")
print("\n" + "=" * 60)
print("Key Patterns:")
print(" - Use index to modify original list")
print(" - Access neighbors with index-1, index+1")
print(" - Build dictionaries with {value: index}")
print(" - Filter/group by index properties (even/odd)")
print("=" * 60)