W Szum
W Szum

Reputation: 171

Printing Inverted Pyramid in Python

I have the following code printing an inverted pyramid using numbers from 0 to 9. However, I'm curious how can I change this code to print numbers in order starting from pyramid's end?

height = 5
num = 0
for i in reversed(range(1, height + 1)):
    print(" " * (height - i), end="")
    for j in range((i - 1) * 2 + 1):
        print(num, end="")
        if num == 9:
            num = 0
        else:
            num += 1
print("\r")

The output of above code is:

012345678
 9012345
  67890
   123
    4

Desired output:

789012345
 0123456
  56789
   234
    1

Upvotes: 0

Views: 936

Answers (3)

adamkwm
adamkwm

Reputation: 1173

I'm not good at math but I found a way to get sum of odd numbers on internet,

1+ 3+ 5+ 7+ 9+ ... + (2n-1) = n2

which may be useful to find the starting number of the inverted pyramid.

def inverted_pyramid(height):
    for h in reversed(range(height)):
        print(" " * (height - h - 1), end = "")
        n = (1 + h ** 2) % 10
        for w in range(1 + h * 2):
            print(n, end = "")
            n += 1
            if n == 10:
                n = 0
        print()

inverted_pyramid(5)

Output:

789012345
 0123456
  56789
   234
    1

Upvotes: 1

Henry Tjhia
Henry Tjhia

Reputation: 752

h = 10
z = [1, 2, 5, 0, 7, 6, 7, 0, 5, 2]

for i in reversed(range(1, h+1)):
    s = ''
    m = (i % 10) - 1
    n = z[m]
    
    for j in range(i, (i-1)+(2*i)):
        s += str(n)
        n = n + 1 if n < 9 else 0   
    else:
        print(f'{s:^{(h-1)+(2*h)}}')
     2345678901234567890     
      56789012345678901      
       012345678901234       
        7890123456789        
         67890123456         
          789012345          
           0123456           
            56789            
             234             
              1

Upvotes: 1

BanjoBenjo
BanjoBenjo

Reputation: 128

If you dont want to calculate the starting number first you could also calculate the lines for a normal pyramid, save each line in a list, and then reverse the list order before printing.

Upvotes: 0

Related Questions