Skip to content

MEDIUM SLICE() EXAMPLES

Python
#!/usr/bin/env python3
"""
MEDIUM SLICE() EXAMPLES
Practical applications and data processing patterns
"""

print("=" * 60)
print("MEDIUM SLICE() - Practical Slice Applications")
print("=" * 60)

# Example 1: Pagination with slices
print("\n1. Implementing Pagination")
print("-" * 40)

items = [f"Item_{i:03d}" for i in range(1, 51)]  # 50 items
page_size = 10
total_pages = (len(items) + page_size - 1) // page_size

print(f"Total items: {len(items)}, Page size: {page_size}\n")

# Create slice objects for each page
for page_num in range(1, 5):  # Show first 4 pages
    start = (page_num - 1) * page_size
    page_slice = slice(start, start + page_size)
    page_items = items[page_slice]
    print(f"Page {page_num}: {page_items[:3]}...{page_items[-2:]} (showing first 3 and last 2)")

# Example 2: Rolling window analysis
print("\n2. Sliding Window (Moving Average)")
print("-" * 40)

temperatures = [72, 75, 78, 76, 74, 77, 80, 82, 79, 77, 75, 73]
window_size = 3

print(f"Daily temperatures: {temperatures}")
print(f"Window size: {window_size} days\n")
print("Day | Window      | Average")
print("----|-------------|--------")

for i in range(len(temperatures) - window_size + 1):
    window = slice(i, i + window_size)
    window_data = temperatures[window]
    avg = sum(window_data) / len(window_data)
    print(f"{i+1:3d} | {window_data} | {avg:6.2f}°F")

# Example 3: Data chunking
print("\n3. Splitting Data into Chunks")
print("-" * 40)

data = list(range(1, 26))  # 1-25
chunk_size = 5

print(f"Data: {data}")
print(f"Chunk size: {chunk_size}\n")

chunks = []
for i in range(0, len(data), chunk_size):
    chunk_slice = slice(i, i + chunk_size)
    chunk = data[chunk_slice]
    chunks.append(chunk)
    print(f"Chunk {len(chunks)}: {chunk}")

# Example 4: Extracting columns from rows
print("\n4. Column Extraction (CSV-like Data)")
print("-" * 40)

# Simulated CSV data
data = [
    "001,Alice,25,NYC",
    "002,Bob,30,LA",
    "003,Charlie,35,Chicago",
    "004,Diana,28,Boston",
    "005,Eve,32,Seattle"
]

print("Raw data:")
for row in data:
    print(f"  {row}")

# Define slices for parsing
rows = [row.split(',') for row in data]

# Extract specific columns
id_col = slice(0, 1)
name_col = slice(1, 2)
age_col = slice(2, 3)

print("\nExtracted names (column 2):")
for row in rows:
    print(f"  {row[name_col][0]}")

print("\nExtracted ages (column 3):")
for row in rows:
    print(f"  {row[age_col][0]}")

# Example 5: Time series slicing
print("\n5. Time-Based Data Slicing")
print("-" * 40)

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
          "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
sales = [100, 120, 150, 180, 200, 190, 210, 230, 220, 200, 180, 250]

print("Monthly sales data:")
for month, sale in zip(months, sales):
    print(f"  {month}: ${sale}")

# Define quarters
Q1 = slice(0, 3)
Q2 = slice(3, 6)
Q3 = slice(6, 9)
Q4 = slice(9, 12)

quarters = [("Q1", Q1), ("Q2", Q2), ("Q3", Q3), ("Q4", Q4)]

print("\nQuarterly totals:")
for name, quarter in quarters:
    quarter_sales = sales[quarter]
    total = sum(quarter_sales)
    avg = total / len(quarter_sales)
    print(f"  {name}: Total=${total}, Average=${avg:.2f}")

# Example 6: Skipping headers/footers
print("\n6. Skipping Headers and Footers")
print("-" * 40)

log_file = [
    "=== LOG START ===",
    "Header: System v1.0",
    "---",
    "2024-01-01: User login",
    "2024-01-02: File uploaded",
    "2024-01-03: Data processed",
    "2024-01-04: Report generated",
    "---",
    "=== LOG END ===",
    "Footer: Total entries 4"
]

print("Raw log:")
for line in log_file:
    print(f"  {line}")

# Extract only data (skip header and footer)
data_only = slice(3, -3)
print("\nData lines only:")
for line in log_file[data_only]:
    print(f"  {line}")

# Example 7: Reverse slicing
print("\n7. Reversing with Slices")
print("-" * 40)

sequence = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(f"Original: {sequence}\n")

# Reverse entire sequence
reverse_all = slice(None, None, -1)
print(f"Reversed:        {sequence[reverse_all]}")

# Reverse middle section
reverse_middle = slice(7, 2, -1)
print(f"Reverse [3-7]:   {sequence[reverse_middle]}")

# Every 2nd in reverse
every_2nd_reverse = slice(None, None, -2)
print(f"Every 2nd (rev): {sequence[every_2nd_reverse]}")

# Example 8: Conditional slicing based on data
print("\n8. Dynamic Slice Creation")
print("-" * 40)

scores = [45, 67, 89, 92, 78, 85, 90, 76, 88, 95]
print(f"Scores: {scores}\n")

# Find where scores go above 80
threshold = 80
above_threshold_indices = [i for i, score in enumerate(scores) if score > threshold]

if above_threshold_indices:
    first_above = above_threshold_indices[0]
    last_above = above_threshold_indices[-1]

    high_scores_slice = slice(first_above, last_above + 1)
    print(f"Scores above {threshold}: {scores[high_scores_slice]}")
    print(f"From index {first_above} to {last_above}")

# Example 9: Batch processing with remainder handling
print("\n9. Batch Processing with Remainder")
print("-" * 40)

tasks = [f"Task{i}" for i in range(1, 23)]  # 22 tasks
batch_size = 5

print(f"Total tasks: {len(tasks)}, Batch size: {batch_size}\n")

batch_num = 1
for i in range(0, len(tasks), batch_size):
    batch_slice = slice(i, min(i + batch_size, len(tasks)))
    batch = tasks[batch_slice]
    print(f"Batch {batch_num} ({len(batch)} items): {batch}")
    batch_num += 1

# Example 10: Multi-level slicing
print("\n10. Nested Structure Slicing")
print("-" * 40)

# Matrix-like data
matrix = [
    [1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10],
    [11, 12, 13, 14, 15],
    [16, 17, 18, 19, 20],
    [25, 26, 27, 28, 29]
]

print("Matrix:")
for row in matrix:
    print(f"  {row}")

# Get first 3 rows
row_slice = slice(3)
print(f"\nFirst 3 rows:")
for row in matrix[row_slice]:
    print(f"  {row}")

# Get middle 3 elements from each of first 3 rows
col_slice = slice(1, 4)
print(f"\nMiddle 3 elements from first 3 rows:")
for row in matrix[row_slice]:
    print(f"  {row[col_slice]}")

print("\n" + "=" * 60)
print("Practical Patterns:")
print("  - Pagination: slice(page*size, (page+1)*size)")
print("  - Windows: slice(i, i+window_size)")
print("  - Skip header: slice(n, None)")
print("  - Skip footer: slice(None, -n)")
print("  - Quarters: slice(month*3, (month+1)*3)")
print("  - Reverse: slice(None, None, -1)")
print("=" * 60)