Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python inverted number pyramid exercise

This is an example of a correct pyramid.

this is how my pyramid has to look like.

I have this exercise as homework but I cant figure it out.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The code i’ve tried so far is this one and I can’t make it inverted:

n = 5
for i in range(n, 0, -1):
       for j in range(n, i-1, -1):
           print(j, end=" ") 
    
       print(" ")

>Solution :

n = int(input("What's the number: "))

for i in range(n, 0, -1):
    for j in range(i, 0, -1):
        print(j, end="")
    print()

Works for me.

The trick is to start the second loop "j" with the decrementing "i" downwards.

Imagine you are doing not a pyramid, but printing

5 4 3 2 1 n times.

Something like

5 4 3 2 1
5 4 3 2 1
5 4 3 2 1
5 4 3 2 1
5 4 3 2 1
5 4 3 2 1
...

You would start i and j at the same index, n, and just repeat the task.

Here, you start j at i, so each time i gets decremented, j starts from the decremented i, thus making a pyramid effect.

Hope you understand 🙂

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading