0

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
2
  • 3
    First, you need to calculate the starting number. It's not too hard - how do you think you could do that? Commented Nov 25, 2020 at 7:13
  • I would use a recursive function. Commented Nov 25, 2020 at 7:24

3 Answers 3

1
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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.