I have a pattern which i printed using below code
Code :
n=5
def pyramidupdown(n):
cnt=0
space=2
lst= [str(row) for row in reversed(range(1,n+1))]
for i in range(1,n+1):
if i == 1:
s=' '.join(lst)
print(s)
else:
lst[cnt]=' '
s=' '.join(lst)
print(s)
cnt = cnt + 1
It prints the pattern below as output :
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
But my issue is with spaces when the n value is defined 2 digit like 15
the pattern is not printed properly
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
14 13 12 11 10 9 8 7 6 5 4 3 2 1
13 12 11 10 9 8 7 6 5 4 3 2 1
12 11 10 9 8 7 6 5 4 3 2 1
11 10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1
8 7 6 5 4 3 2 1
7 6 5 4 3 2 1
6 5 4 3 2 1
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
Expected output :
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
14 13 12 11 10 9 8 7 6 5 4 3 2 1
13 12 11 10 9 8 7 6 5 4 3 2 1
12 11 10 9 8 7 6 5 4 3 2 1
11 10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1
8 7 6 5 4 3 2 1
7 6 5 4 3 2 1
6 5 4 3 2 1
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
what changes do i need to make in existing code to print properly the pattern
>Solution :
I would just do it like this:
def pyramidupdown(n):
for i in range(n,0,-1):
lst = []
for j in range(n,0,-1):
s = str(j)
lst.append(s if j <= i else ' '*len(s))
print(" ".join(lst))