⚡ TL;DR
Print the palindromic number pyramid pattern in Python. Complete working code, expected output, and a clear step-by-step explanation for beginners learning loops.
The Palindromic Number Pyramid pattern is a classic loop exercise. Here’s the complete implementation in Python with working code and output.
Pattern to Print
1
121
12321
1234321
123454321Implementation
def palindromic_pyramid(n):
for i in range(1, n + 1):
print(' ' * (n - i), end='')
for j in range(1, i + 1): print(j, end='')
for j in range(i - 1, 0, -1): print(j, end='')
print()
palindromic_pyramid(5)Output
1
121
12321
1234321
123454321How It Works
Print ascending 1..i then descending i-1..1 on each row, right-aligned with leading spaces.
Practice Variations
- Try printing the pattern with a different character (e.g.,
#or+) - Modify the code to accept the pattern size as user input
- Combine this pattern with its inverse to create a more complex shape
Complexity
- Time: O(n²) — the grid or line count grows quadratically
- Space: O(1) — only loop counters are needed
Related Patterns
- Palindromic Number Pyramid in Dart
- Palindromic Number Pyramid in Go
- Palindromic Number Pyramid in Swift
- Number Pyramid in Python
- Number Triangle in Python
- Increasing Number Triangle in Python
FAQ
How do you print the Palindromic Number Pyramid pattern in Python?
Use nested loops: the outer loop walks through the rows while the inner loop prints the characters or values for each row. The complete Python implementation with expected output is shown in the sections above.
What is the time complexity of the Palindromic Number Pyramid pattern in Python?
The time complexity is O(n²) and the space complexity is O(1), since the pattern is built with a fixed number of loop counters and printed row by row.
Happy coding!
