π Python Pattern Challenge — Day 12
Pattern printing is a great way to improve your Python logic, nested loops, mathematical thinking, and problem-solving skills. For Day 12, let's move beyond simple star patterns and create a number pattern based on Pascal's Triangle.
The challenge is to generate each row dynamically, where every number is calculated from the values of the previous row.
Today's Challenge
Write a Python program to print:
Best and cleanest code will be rewarded! π
Solution 1 — Using Nested for Loops
n = 6 for i in range(n): num = 1 print(" " * (n - i - 1), end="") for j in range(i + 1): print(num, end=" ") num = num * (i - j) // (j + 1) print()
How it works:
The variable num starts with:
num = 1For every next value, we calculate:
num = num * (i - j) // (j + 1)This formula generates the next value of the current Pascal's Triangle row.
For example:
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
The spacing:
keeps the triangle centered." " * (n - i - 1)
Solution 2 — Using Lists
n = 6 row = [1] for i in range(n): print(" " * (n - i - 1), end="") print(*row) row = [ row[j] + row[j + 1] for j in range(len(row) - 1) ] row = [1] + row + [1]
How it works:
We start with:
row = [1]Then every new row is created by adding neighboring values from the previous row.
For example:
1 3 3 1produces:
1 4 6 4 1because:
1 + 3 = 4Then 1 is added to both ends.
Solution 3 — Using a Function
def pascal(n): row = [1] for i in range(n): print(" " * (n - i - 1), end="") print(*row) row = [1] + [ row[j] + row[j + 1] for j in range(len(row) - 1) ] + [1] pascal(6)
How it works:
Putting the pattern inside a function makes it reusable.
You can easily change:
pascal(6)to:
pascal(10)to generate more rows.
⚡ Short & Clean Code
r = [1] for i in range(6): print(" " * (5-i), *r) r = [1] + [r[j] + r[j+1] for j in range(i)] + [1]
π₯ This compact version generates the same Pascal's Triangle pattern using a single main loop.
π Challenge Yourself
Can you modify this pattern:
- Generate 10 or 15 rows?
- Create Pascal's Triangle using only nested loops?
- Take the number of rows using input()?
- Print the triangle upside down?
- Replace the numbers with *?
- Calculate the sum of every row?
- Find the largest number in the generated triangle?
Drop your solution below! π
12 Days. 12 Patterns. Stronger Python Logic. ππ₯
Learn • Practice • Grow with CLCODING

0 Comments:
Post a Comment