Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Number Patterns Recursively

Generate increasing number rows with recursive helpers. Students separate a row-size function from a per-row number function and trace each helper's boundary.

IntermediatePhase 3 - Level 3: Pattern RecursionExample 5 of 10
number-patterns-recursively.py
1def print_numbers(n, current=1):
2 # Base case
3 if current > n:
4 return
5
6 # Print current number
7 print(current, end="")
8 # Recurse
9 print_numbers(n, current + 1)
10
11def print_pattern(n, row=1):
12 # Base case
13 if row > n:
14 return
15
16 # Print row
17 print_numbers(row)
18 print()
19 # Recurse
20 print_pattern(n, row + 1)
21
22# Test
23n = int(input("Enter rows: "))
24print_pattern(n)

Output

Enter rows: 4
1
12
123
1234

In this one

  • Separate row and value recursion
  • Restart a current argument
  • Bound both helpers

How it works

  1. 1

    Choose the next row width in print_pattern.

  2. 2

    Print one through that width with print_numbers.

  3. 3

    End the line and request the next row.

Edge cases

What if n = 0?

What if n = 0?

No rows print.

Does numbering continue across rows?

Does numbering continue across rows?

No. The default current value restarts at one.

What's going on

print_pattern chooses the row width. print_numbers starts at one and prints successive current values until current exceeds that width.

Each row ends before the next row is requested, giving 1, 12, 123 for three rows. Starting current at one for every helper call restarts numbering. Both helpers use the call stack and need their stopping comparisons.

What if n = 0? No rows print.

Does numbering continue across rows? No. The default current value restarts at one.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does print_numbers(row) control?

Pick an answer to check it.

Question 2

What if n = 0?

Pick an answer to check it.

Questions people ask

What if n = 0?

No rows print.

Does numbering continue across rows?

No. The default current value restarts at one.

What does print_numbers(row) control?

Values from one through the current row.