π Python Pattern Challenge — Day 15
Pattern printing is a simple but powerful way to improve your Python loops, spacing, repetition, and logical thinking. For Day 15, let's create a simple Number 1 Diamond Pattern.
The pattern uses only the number 1, but the number of 1s increases toward the center and then decreases, creating a symmetric diamond.
Today's Challenge
Write a Python program to print:
Best and cleanest code will be rewarded! π
Solution 1 — Using Nested for Loops
n = 5 for i in range(1, n + 1): print(" " * (n - i), end="") for j in range(i): print("1", end=" ") print() for i in range(n - 1, 0, -1): print(" " * (n - i), end="") for j in range(i): print("1", end=" ") print()
How it works
The first loop creates the increasing half:
11 1 1 1 1 1 1 1 1 1 1 1 1 1
The second loop creates the decreasing half:
1 1 1 11 1 1 1 1 1
This creates the complete symmetric diamond.
Solution 2 — Using String Multiplication
n = 5 for i in range(1, n + 1): print(" " * (n - i) + "1 " * i) for i in range(n - 1, 0, -1): print(" " * (n - i) + "1 " * i)
How it works
This line:
" " * (n - i)controls the indentation.
And:
"1 " * iprints the required number of 1s.
For example, when i = 3:
1 1 1is generated automatically.
Solution 3 — Using a Single Loop
n = 5 for i in list(range(1, n + 1)) + list(range(n - 1, 0, -1)): print(" " * (n - i) + "1 " * i)
How it works
Instead of using two separate loops, we create one sequence:
[1, 2, 3, 4, 5, 4, 3, 2, 1]Each value determines how many 1s should appear on that row.
This makes the code short and easy to understand.
Solution 4 — Using a Function
def number_one_diamond(n): for i in list(range(1, n + 1)) + list(range(n - 1, 0, -1)): print(" " * (n - i) + "1 " * i) number_one_diamond(5)
Now you can easily change the size:
number_one_diamond(7)and generate a larger pattern.
⚡ Short & Clean Code
for i in [1, 2, 3, 4, 5, 4, 3, 2, 1]: print(" " * (5-i) + "1 " * i)
π₯ Just one loop is enough to create the complete pattern.
π Challenge Yourself
Can you modify this pattern:
- Take n from the user using input()?
- Replace 1 with *?
- Replace 1 with letters?
- Create the same pattern using a while loop?
- Create a hollow version of the diamond?
- Generate the increasing/decreasing sequence without manually writing it?
Drop your solution below! π
15 Days. 15 Patterns. Stronger Python Logic. ππ₯
Learn • Practice • Grow with CLCODING

0 Comments:
Post a Comment