Step 01 Beginner Problems — Patterns
Pattern 13 — Increasing Number Triangle Pattern
Floyd's triangle: a growing number triangle where the counting never restarts. A single counter starts at 1 and keeps incrementing across the entire figure, so rows of length 1, 2, 3, ... consume consecutive numbers and the last entry of the whole triangle is the triangular number n(n+1)/2.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
How to think about it
Number the rows i = 0, 1, ..., n-1; row i has i + 1 entries. Keep one variable, num, initialised to 1 before the outer loop. The inner loop appends num to the current row and increments it, i + 1 times per row. Because num lives outside both loops, its value carries across rows — that single scoping decision is the entire difference from Pattern 3, where each row recomputed its values from the column index. Before row i starts, the counter equals 1 + i(i+1)/2, giving the row-start values 1, 2, 4, 7, 11.
Code
The counter num is created once, before the loops. Each row collects i + 1 successive values into a list (incrementing num after each) and prints them joined. Moving the num = 1 line inside the outer loop would reset it every row and reproduce Pattern 3 — scope is the algorithm here.
def pattern(n):
num = 1
for i in range(n):
row = []
for j in range(i + 1):
row.append(str(num))
num += 1
print(" ".join(row))Key points
- One running counter across all rows: never reset it inside the outer loop.
- Row i has i + 1 entries; the first entry of row i is 1 + i(i+1)/2.
- The final printed number is the triangular number n(n+1)/2 — for n = 5, that is 15.
- Variable scope is the whole trick: state created outside the loop persists, state inside resets.
- Two-digit numbers (10+) will misalign columns in a naive join — expected in the classic version.