S3Q2 · Pattern Printing - Z Pattern¶
⚡ Quick Reference
Type: Full I/O - pattern printing
Core idea: top and bottom rows are full stars; diagonal rows have a star at position n - i (0-indexed) with leading spaces only - no trailing spaces.
n = int(input())
for i in range(1, n + 1):
if i == 1 or i == n:
print("*" * n)
else:
print(" " * (n - i) + "*")
Key rules:
- Row 1 and row n: full row of n stars
- Rows 2 to n-1: n - i leading spaces then * (no trailing spaces)
- i is 1-indexed
Problem Statement¶
Problem (I/O type)
Given n, print a Z-shaped pattern:
- Top row: n stars
- Diagonal: star moves from right to left as rows increase
- Bottom row: n stars
- No trailing spaces after the last * on any line
Examples:
5
*****
*
*
*
*****
4
****
*
*
****
Deriving the pattern¶
For n = 5, mark where the * appears on each row (1-indexed):
Row i |
Type | Leading spaces | Star position |
|---|---|---|---|
| 1 | Top border | - | All n stars |
| 2 | Diagonal | 3 | n - i = 3 |
| 3 | Diagonal | 2 | n - i = 2 |
| 4 | Diagonal | 1 | n - i = 1 |
| 5 | Bottom border | - | All n stars |
The diagonal star starts at the second-to-last column (n-2 in 0-indexed, which is n-i spaces for i=2) and moves one step left each row, reaching column 0 at row n-1.
Formula for diagonal rows: " " * (n - i) + "*"
No trailing spaces
The problem explicitly says no space after the last *. Since the diagonal rows have their star at a position left of the rightmost column, there would be trailing spaces if you tried to pad to width n. The formula " " * (n - i) + "*" naturally produces no trailing spaces.
Tracing n = 5¶
| i | n - i spaces |
Row printed |
|---|---|---|
| 1 | - (border) | ***** |
| 2 | 3 | ···* |
| 3 | 2 | ··* |
| 4 | 1 | ·* |
| 5 | - (border) | ***** |
(dots represent spaces)
Tracing n = 3¶
| i | Row printed |
|---|---|
| 1 | *** |
| 2 | ·* (1 space + star) |
| 3 | *** |
Solution approaches¶
Common mistake - trailing spaces¶
A common mistake is printing each row padded to width n:
# ❌ Wrong - adds trailing spaces to diagonal rows
print(f"{'*':>{n - i + 1}:<{n}}") # pads right side too
The problem says no trailing spaces. Always end diagonal rows right after the *.
Key takeaways¶
Border rows vs diagonal rows
Pattern problems almost always have special cases for the first and last row. Handle them with if i == 1 or i == n and apply the general formula for everything in between.
No trailing spaces - end at the star
" " * (n - i) + "*" stops right after the star. Never pad to the full row width when trailing spaces are forbidden.
Diagonal moves left as i increases
For Z: star starts at the right and moves left. Leading spaces = n - i - decreases as i increases. Contrast with triangles where stars grow; here only one star moves.