๐ Python Pattern Challenge — Day 50 | Number Square Spiral Pattern
Welcome to Day 50 of the Python Pattern Challenge! ๐๐
We've reached an exciting milestone — 50 days of learning, practicing, and improving Python programming logic!
For Day 50, we're creating an interesting Number Square Spiral Pattern using Python. In this pattern, numbers are arranged around the outer boundary of a square, moving clockwise from the top-left corner.
The sequence starts from 1, moves across the top row, continues down the right side, travels backward along the bottom, and finally moves upward along the left side.
This challenge is perfect for understanding nested loops, matrix indexing, boundary conditions, and logical thinking.
๐ฏ Today's Challenge
Write a Python program to print exactly the following pattern:
๐ป Python Solution
n = 5 matrix = [[0] * n for _ in range(n)] num = 1 for j in range(n): matrix[0][j] = num num += 1 for i in range(1, n): matrix[i][n - 1] = num num += 1 for j in range(n - 2, -1, -1): matrix[n - 1][j] = num num += 1 for i in range(n - 2, 0, -1): matrix[i][0] = num num += 1 for row in matrix: print(" ".join(f"{x:2}" if x else " " for x in row))
๐ง How It Works
1. Creating an empty matrix
matrix = [[0] * n for _ in range(n)]
This creates a 5 × 5 matrix filled with zeros. These zeros represent empty positions.
2. Filling the top row
matrix = [[0] * n for _ in range(n)]for j in range(n): matrix[0][j] = num num += 1
The first loop places numbers from 1 to 5 across the top row.
3. Filling the right column
for i in range(1, n): matrix[i][n - 1] = num num += 1
This loop fills the right boundary from top to bottom with numbers 6, 7, and 8.
4. Filling the bottom row
for j in range(n - 2, -1, -1): matrix[n - 1][j] = num num += 1
The loop moves from right to left, placing numbers 9 through 13 along the bottom.
5. Filling the left column
for i in range(n - 2, 0, -1): matrix[i][0] = num num += 1
This fills the remaining left-side positions with numbers 14, 15, and 16.
6. Printing the final matrix
for row in matrix: print(" ".join(f"{x:2}" if x else " " for x in row))
This prints each row while maintaining proper spacing and leaving the inner positions empty.
๐ Challenge Yourself
Increase the square size to 7 × 7.
Create an anticlockwise number pattern.
Fill the entire matrix instead of just the boundary.
Replace numbers with alphabets.
Try creating the pattern using a single loop and conditional statements.
๐ก Key Takeaway
Number patterns are an excellent way to understand how matrices, nested loops, indexing, and boundary conditions work together.
By practicing these challenges, you can develop stronger programming logic and learn to solve more complex problems step by step.
50 Days. 50 Patterns. Stronger Python Logic. ๐๐ฅ
Thank you for being part of this journey!
Learn • Practice • Grow with CLCODING
not


0 Comments:
Post a Comment