Reputation:
I am trying to print below pyramid pattern. But not clicking how to build logic for it ?
Pattern :
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
I have tried this code seems like this is not a right approach to get it.Any solution is appreciated
import numpy as np
n = 5
cnt=0
var = np.arange(1,n+1)
for row in range(1,n+1):
print(var[::-1][cnt:])
cnt= cnt + 1
Output of above pattern:
[5 4 3 2 1]
[4 3 2 1]
[3 2 1]
[2 1]
[1]
Upvotes: 1
Views: 138
Reputation: 1314
You can create a function to reduce overall complexity
def pyramid(height):
L = 0
for i in range(height):
s = ' '.join(map(str, range(height-i, 0, -1)))
L = max(L, len(s))
print(s.rjust(L))
height = int(input('Enter the height of the Pyramid : '))
pyramid(height)
Upvotes: 1
Reputation: 1932
Any solution? Ok:
>>> print("\n".join([ "{:>10}".format(" ".join([ str(x) for x in range(n,0,-1) ])) for n in range(5,0,-1) ]))
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
Upvotes: 0
Reputation: 260480
Do you really need/want to use numpy?
This is easily achievable using pure python. The logic is to add spaces on the left to pad (you could also use string functions like rjust
):
n = 5
for i in range(n):
print(' '*i + ' '.join(map(str, range(n-i, 0, -1))))
output:
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
NB. if you have double digits, you should use rjust
:
n = 15
L = 0
for i in range(n):
s = ' '.join(map(str, range(n-i, 0, -1)))
L = max(L, len(s))
print(s.rjust(L))
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
Upvotes: 1