Python Program to Print Butterfly Star Pattern
for loops that print stars and spaces in a mirrored shape; for example, use 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
Top half, i=1
Print '*' * 1 + ' ' * 4 + '*' * 1 => '* *'
Top half, i=2
Print '*' * 2 + ' ' * 2 + '*' * 2 => '** **'
Top half, i=3
Print '*' * 3 + ' ' * 0 + '*' * 3 => '******'
Bottom half, i=3
Print '*' * 3 + ' ' * 0 + '*' * 3 => '******'
Bottom half, i=2
Print '*' * 2 + ' ' * 2 + '*' * 2 => '** **'
Bottom half, i=1
Print '*' * 1 + ' ' * 4 + '*' * 1 => '* *'
| i | Stars Left | Spaces | Stars Right | Line Output |
|---|---|---|---|---|
| 1 | * | * | * * | |
| 2 | ** | ** | ** ** | |
| 3 | *** | *** | ****** | |
| 3 | *** | *** | ****** | |
| 2 | ** | ** | ** ** | |
| 1 | * | * | * * |
Why This Works
Step 1: Stars on left and right
We print stars on both sides equal to the current line number using '*' * i to create the wings of the butterfly.
Step 2: Spaces in the middle
The spaces between stars are twice the difference between total lines and current line, 2 * (n - i), to keep the shape symmetric.
Step 3: Top and bottom halves
The top half increases stars and decreases spaces, while the bottom half reverses this to complete the butterfly shape.
Alternative Approaches
n = 5 for i in range(1, 2*n + 1): if i <= n: stars = i else: stars = 2*n - i + 1 spaces = 2*(n - stars) print('*' * stars + ' ' * spaces + '*' * stars)
def print_half(n, start, end, step): for i in range(start, end, step): print('*' * i + ' ' * (2 * (n - i)) + '*' * i) n = 5 print_half(n, 1, n+1, 1) print_half(n, n, 0, -1)
Complexity: O(n^2) time, O(1) space
Time Complexity
The program uses two loops each running up to n times, so the time complexity is O(n^2).
Space Complexity
No extra space proportional to input size is used; only variables for counters, so space complexity is O(1).
Which Approach is Fastest?
All approaches have similar time complexity; using a single loop with condition may be slightly faster but less readable.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Two separate loops | O(n^2) | O(1) | Clear structure, easy to understand |
| Single loop with condition | O(n^2) | O(1) | Compact code, slight speed gain |
| Function for halves | O(n^2) | O(1) | Reusable and clean code |