-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path01_hollow_pyramid_star_pattern.py
More file actions
50 lines (41 loc) · 1.41 KB
/
01_hollow_pyramid_star_pattern.py
File metadata and controls
50 lines (41 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Solution:
def hollow_pyramid_method1(self, rows):
if rows < 5:
print("Value of rows should be greater than or equal to 5 to print hollow star pattern")
return
total_width = 2 * rows - 1
mid = total_width // 2
cur_row = 0
while cur_row < rows:
line = [' '] * total_width
if cur_row == 0:
line[mid] = '*'
elif cur_row == rows - 1:
# Last row: all stars
for i in range(total_width):
line[i] = '*'
else:
left = mid - cur_row
right = mid + cur_row
line[left] = '*'
line[right] = '*'
print(''.join(line))
cur_row += 1
# More optimal approach
def hollow_pyramid_method2(self, rows):
if rows < 5:
print("Value of rows should be greater than or equal to 5 to print hollow star pattern")
return
for i in range(rows):
if i == 0:
line = '*'
elif i == rows - 1:
line = '*' * (2 * rows - 1)
else:
line = '*' + ' ' * (2 * i - 1) + '*'
print(line.center(2 * rows - 1))
if __name__ == "__main__":
obj = Solution()
num_rows = int(input("Enter the number of rows for the hollow pyramid: "))
obj.hollow_pyramid_method1(num_rows)
obj.hollow_pyramid_method2(num_rows)