Python Program to Print Sandglass Star Pattern
for loops that first print decreasing stars and then increasing stars, like this: for i in range(n, 0, -1): print(' ' * (n - i) + '*' * (2 * i - 1)) for i in range(2, n + 1): print(' ' * (n - i) + '*' * (2 * i - 1)).Examples
How to Think About It
Algorithm
Code
n = int(input()) for i in range(n, 0, -1): print(' ' * (n - i) + '*' * (2 * i - 1)) for i in range(2, n + 1): print(' ' * (n - i) + '*' * (2 * i - 1))
Dry Run
Let's trace input n=3 through the code
First loop i=3
Print 0 spaces and 5 stars: '*****'
First loop i=2
Print 1 space and 3 stars: ' ***'
First loop i=1
Print 2 spaces and 1 star: ' *'
Second loop i=2
Print 1 space and 3 stars: ' ***'
Second loop i=3
Print 0 spaces and 5 stars: '*****'
| Loop | i | Spaces | Stars | Printed Line |
|---|---|---|---|---|
| First loop | 3 | 0 | 5 | ***** |
| First loop | 2 | 1 | 3 | *** |
| First loop | 1 | 2 | 1 | * |
| Second loop | 2 | 1 | 3 | *** |
| Second loop | 3 | 0 | 5 | ***** |
Why This Works
Step 1: Decreasing stars with spaces
The first loop prints lines with stars decreasing from the maximum count, adding spaces before stars to center the pattern.
Step 2: Increasing stars with spaces
The second loop prints lines with stars increasing from one star back to the maximum, again adding spaces to keep symmetry.
Step 3: Star count calculation
Each line's star count is calculated as 2 * i - 1 to maintain the sandglass shape with odd number of stars.
Alternative Approaches
n = int(input()) i = n while i > 0: print(' ' * (n - i) + '*' * (2 * i - 1)) i -= 1 i = 2 while i <= n: print(' ' * (n - i) + '*' * (2 * i - 1)) i += 1
n = int(input()) for i in range(1, 2 * n): if i <= n: stars = 2 * (n - i + 1) - 1 spaces = i - 1 else: stars = 2 * (i - n) - 1 spaces = 2 * n - i - 1 print(' ' * spaces + '*' * stars)
Complexity: O(n^2) time, O(1) space
Time Complexity
The program uses two loops each running up to n times, and each line prints up to 2n-1 characters, resulting in O(n^2) time.
Space Complexity
The program uses only a few variables and prints directly, so space complexity is O(1).
Which Approach is Fastest?
All approaches have similar time complexity; using for loops is more readable, while a single loop with conditions is more compact but less clear.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loops (main) | O(n^2) | O(1) | Readability and simplicity |
| While loops | O(n^2) | O(1) | Beginners preferring while syntax |
| Single loop with conditions | O(n^2) | O(1) | Compact code, slightly harder to read |