S3Q2 · Zigzag Number Grid¶
⚡ Quick Reference
Type: Full I/O - pattern printing
Core idea: odd rows go left to right, even rows go right to left. i % 2 decides the direction.
n = int(input())
row = list(range(1, n + 1))
for i in range(1, n + 1):
print(*(row if i % 2 == 1 else row[::-1]))
Key rules:
- Rows are 1-indexed: row 1, 2, 3, …
- i % 2 == 1 (odd) → 1 2 3 ... n
- i % 2 == 0 (even) → n n-1 ... 1
- print(*iterable) prints space-separated values automatically
Problem Statement¶
Problem (I/O type)
Read an integer n. Print an n × n grid where odd rows go left to right and even rows go right to left.
Example:
4
1 2 3 4
4 3 2 1
1 2 3 4
4 3 2 1
Understanding the pattern¶
Every row contains the same numbers 1 through n - the only difference is direction:
Row 1 (odd) → 1 2 3 4 range(1, n+1)
Row 2 (even) ← 4 3 2 1 range(n, 0, -1) or row[::-1]
Row 3 (odd) → 1 2 3 4
Row 4 (even) ← 4 3 2 1
Key insight: i % 2 == 1 → left to right | i % 2 == 0 → right to left
Tracing n = 4¶
i |
i % 2 |
Direction | Output |
|---|---|---|---|
| 1 | 1 (odd) | → left to right | 1 2 3 4 |
| 2 | 0 (even) | ← right to left | 4 3 2 1 |
| 3 | 1 (odd) | → left to right | 1 2 3 4 |
| 4 | 0 (even) | ← right to left | 4 3 2 1 |
Solution approaches¶
Key takeaways¶
i % 2 controls direction
Odd row → print left to right (range(1, n+1)). Even row → print right to left (range(n, 0, -1) or row[::-1]). Build the row once, reuse it every iteration.
row[::-1] reverses in one step
Slicing with step -1 creates a reversed copy without modifying the original. row stays [1, 2, 3, 4] for the next odd row.
print(*iterable) adds spaces automatically
The * unpacks the list and print() joins elements with spaces by default. No manual " ".join() or loop needed.