Python Program to Print Butterfly Pattern
for i in range(1, n+1): print('*' * i + ' ' * (2*(n-i)) + '*' * i) for the top half and a similar loop for the bottom half.Examples
How to Think About It
Algorithm
Code
n = 5 for i in range(1, n + 1): print('*' * i + ' ' * (2 * (n - i)) + '*' * i) for i in range(n, 0, -1): print('*' * i + ' ' * (2 * (n - i)) + '*' * i)
Dry Run
Let's trace n=3 through the code to see how the butterfly pattern forms.
Top half, line 1
Print 1 star, 4 spaces, 1 star: '* *'
Top half, line 2
Print 2 stars, 2 spaces, 2 stars: '** **'
Top half, line 3
Print 3 stars, 0 spaces, 3 stars: '******'
Bottom half, line 3
Print 3 stars, 0 spaces, 3 stars: '******'
Bottom half, line 2
Print 2 stars, 2 spaces, 2 stars: '** **'
Bottom half, line 1
Print 1 star, 4 spaces, 1 star: '* *'
| Line | Stars Left | Spaces | Stars Right | Output |
|---|---|---|---|---|
| 1 | 1 | 4 | 1 | * * |
| 2 | 2 | 2 | 2 | ** ** |
| 3 | 3 | 0 | 3 | ****** |
| 3 | 3 | 0 | 3 | ****** |
| 2 | 2 | 2 | 2 | ** ** |
| 1 | 1 | 4 | 1 | * * |
Why This Works
Step 1: Stars on both sides
Each line prints stars on the left and right sides using * i where i is the current line number.
Step 2: Spaces in the middle
Spaces between stars decrease as the line number increases, calculated by 2 * (n - i) to keep symmetry.
Step 3: Top and bottom halves
The top half builds up stars and reduces spaces, while the bottom half reverses this to complete the butterfly shape.
Alternative Approaches
n = 5 for i in range(1, n + 1): print(''.join(['*' for _ in range(i)]) + ' ' * (2 * (n - i)) + ''.join(['*' for _ in range(i)])) for i in range(n, 0, -1): print(''.join(['*' for _ in range(i)]) + ' ' * (2 * (n - i)) + ''.join(['*' for _ in range(i)]))
def print_line(i, n): print('*' * i + ' ' * (2 * (n - i)) + '*' * i) n = 5 for i in range(1, n + 1): print_line(i, n) for i in range(n, 0, -1): print_line(i, n)
Complexity: O(n^2) time, O(1) space
Time Complexity
The program uses two loops each running n times, and each line prints up to 2*n characters, resulting in O(n^2) time.
Space Complexity
The program uses constant extra space for variables and prints directly, so space complexity is O(1).
Which Approach is Fastest?
All approaches have similar time complexity; using string multiplication is fastest and simplest for this pattern.
| Approach | Time | Space | Best For |
|---|---|---|---|
| String multiplication | O(n^2) | O(1) | Simplicity and speed |
| List comprehension with join | O(n^2) | O(1) | Flexibility in building strings |
| Function abstraction | O(n^2) | O(1) | Readability and reuse |