S1Q3 · Replace Middle with N Times Middle¶
⚡ Quick Reference
Function: replace_middle_with_n_times_middle(t: tuple, n: int) -> tuple
Core idea: find the middle index, slice around it, insert n copies of the middle element.
def replace_middle_with_n_times_middle(t: tuple, n: int) -> tuple:
mid = len(t) // 2
return t[:mid] + (t[mid],) * n + t[mid+1:]
Key rules:
- Input always has odd length → middle index = len(t) // 2
- (t[mid],) * n creates a tuple of n copies
- Concatenate: before + copies + after
Problem Statement¶
Problem
Write a function replace_middle_with_n_times_middle(t, n) that replaces the middle element of the odd-length tuple t with n copies of itself.
Examples:
t=(1, 2, 3, 4, 5), n=5
(1, 2, 3, 3, 3, 3, 3, 4, 5)
t=(1, 2, 3), n=4
(1, 2, 2, 2, 2, 3)
Understanding the problem¶
For t = (1, 2, 3, 4, 5):
len(t) = 5 → mid = 5 // 2 = 2
t[mid] = t[2] = 3
t[:2] = (1, 2)
(3,) * 5 = (3, 3, 3, 3, 3)
t[3:] = (4, 5)
Result: (1, 2) + (3,3,3,3,3) + (4, 5) = (1, 2, 3, 3, 3, 3, 3, 4, 5)
(element,) * n - single-element tuple repeated
To create a tuple of n copies of a value: (value,) * n. The trailing comma after value makes it a tuple (not parentheses). Without the comma: (value) * n is just value * n - a number multiplied.
Tracing both examples¶
t=(1,2,3,4,5), n=5:
mid = 2, t[mid] = 3
t[:2] + (3,)*5 + t[3:]
= (1,2) + (3,3,3,3,3) + (4,5)
= (1, 2, 3, 3, 3, 3, 3, 4, 5)
t=(1,2,3), n=4:
Solution approaches¶
def replace_middle_with_n_times_middle(t: tuple, n: int) -> tuple:
l = list(t)
mid = len(l) // 2
l[mid:mid+1] = [l[mid]] * n # replace one element with n copies
return tuple(l)
Convert to list (mutable), use slice assignment to replace the middle element with n copies, convert back. The slice l[mid:mid+1] = [...] replaces exactly one element.
Key takeaways¶
(value,) * n - tuple repetition
The trailing comma makes (value,) a single-element tuple. Multiplying by n gives n copies. Without the comma, (value) * n is arithmetic, not a tuple.
len(t) // 2 for odd-length middle
For any odd-length sequence, integer division by 2 gives the exact middle index: length 3 → index 1, length 5 → index 2, length 7 → index 3.
l[mid:mid+1] = [...] for in-place replacement
Slice assignment l[i:i+1] = new_elements replaces exactly one element with any number of elements - a flexible in-place substitution pattern.