Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python program to show diamond pattern with 2n-1 lines
A diamond pattern is a symmetric arrangement of asterisks that expands from one star to n stars, then contracts back to one star. The pattern consists of 2n-1 lines total, with the widest part containing n asterisks.
Understanding the Pattern
For n = 5, the diamond pattern looks like ?
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
The pattern has two parts ?
- Expanding part: Lines 1 to n (1, 2, 3, ..., n asterisks)
- Contracting part: Lines n+1 to 2n-1 (n-1, n-2, ..., 1 asterisks)
Algorithm
To create the diamond pattern ?
- For i from 1 to n: print i asterisks centered in 2n-1 character width
- For i from n-1 to 1: print i asterisks centered in 2n-1 character width
Implementation
def solve(n):
# Expanding part (1 to n asterisks)
for i in range(1, n + 1):
print(('* ' * i).center(2 * n - 1))
# Contracting part (n-1 to 1 asterisks)
for i in range(n - 1, 0, -1):
print(('* ' * i).center(2 * n - 1))
# Test with n = 5
n = 5
solve(n)
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
How It Works
The center() method centers the string within the specified width. For each line ?
-
'* ' * icreates a string with i asterisks separated by spaces -
.center(2 * n - 1)centers this string in a field of width 2n-1 - The width 2n-1 ensures proper spacing for the diamond shape
Example with Different Values
def solve(n):
for i in range(1, n + 1):
print(('* ' * i).center(2 * n - 1))
for i in range(n - 1, 0, -1):
print(('* ' * i).center(2 * n - 1))
# Test with n = 3
print("Diamond pattern for n = 3:")
solve(3)
print("\nDiamond pattern for n = 7:")
solve(7)
Diamond pattern for n = 3:
*
* *
* * *
* *
*
Diamond pattern for n = 7:
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
Conclusion
The diamond pattern uses Python's center() method to create symmetric spacing. The pattern always has 2n-1 lines with the middle line containing n asterisks, creating a perfect diamond shape.
Advertisements
