S3Q2 · Pattern Printing - W Pattern¶
⚡ Quick Reference
Type: Full I/O - pattern printing
Core idea: row i (1-indexed from top) has n-i spaces between | and /, then 2*(i-1) inner spaces, then \, then n-i spaces before the closing |.
n = int(input())
for i in range(1, n + 1):
pad = " " * (n - i)
inner = " " * (2 * (i - 1))
print(f"|{pad}/{inner}\\{pad}|")
Key rules:
- Outer | on both sides of every row
- / and \ move diagonally inward as rows increase
- Padding outside / and \: n - i spaces (decreases row by row)
- Inner spaces between / and \: 2 * (i - 1) (increases row by row)
- Escape \ in Python strings as \\
Problem Statement¶
Problem (I/O type)
Given n, print a W-shaped pattern with n rows. Each row has | on both sides, with / and \ moving diagonally from the outside inward as rows increase.
Examples:
3
| /\ |
| / \ |
|/ \|
2
| /\ |
|/ \|
1
|/\|
Deriving the pattern¶
Look at each row for n = 3:
Row 1: | /\ | → | + 2 spaces + / + 0 inner spaces + \ + 2 spaces + |
Row 2: | / \ | → | + 1 space + / + 2 inner spaces + \ + 1 space + |
Row 3: |/ \| → | + 0 spaces + / + 4 inner spaces + \ + 0 spaces + |
Two formulas for row i (1-indexed from top):
| Part | Formula | Row 1 | Row 2 | Row 3 |
|---|---|---|---|---|
| Outer padding (each side) | n - i |
2 | 1 | 0 |
Inner spaces (between / and \) |
2 * (i - 1) |
0 | 2 | 4 |
Row structure: | + (n-i) spaces + / + 2*(i-1) spaces + \ + (n-i) spaces + |
Why 2*(i-1) inner spaces?
The / and \ both move one step outward each row - / moves one step left, \ moves one step right. Together they create 2 extra inner spaces per row. At row 1 there are 0 inner spaces; at row 2 there are 2; at row 3 there are 4 - each time increasing by 2.
Tracing n = 3¶
| i | n-i |
2*(i-1) |
Row printed |
|---|---|---|---|
| 1 | 2 | 0 | \| /\ \| |
| 2 | 1 | 2 | \| / \ \| |
| 3 | 0 | 4 | \|/ \\| |
(backslash shown escaped for clarity)
The backslash problem¶
In Python, \ is an escape character in strings. To print a literal backslash you must write \\:
In an f-string:
Solution approaches¶
n = int(input())
for i in range(1, n + 1):
pad = " " * (n - i)
inner = " " * (2 * (i - 1))
print(f"|{pad}/{inner}\\{pad}|")
Clean and readable. Two variables - pad for outer spacing, inner for the space between / and \.
Verifying with n = 1¶
i = 1: n - i = 0, 2*(i-1) = 0
Row: | + + `/` + + \ + ` +|=|/|`
Key takeaways¶
Escape backslash as \\
\ is an escape character in Python strings. Always write \\ to get a literal backslash in output. In f-strings, f"{\\"} is not valid - use a variable: bs = "\\"; f"{bs}" or write "\\" directly outside the braces.
Symmetric padding on both sides
The outer padding is the same on the left and right of each row (n - i). Store it in one variable and reuse it for both sides - less chance of a typo.
Inner spaces grow by 2 per row
Each step down, / moves one left and \ moves one right - together adding 2 inner spaces. The formula 2*(i-1) captures this: 0 at row 1, 2 at row 2, 4 at row 3, …