Home > OS >  How to invert the result of this for loop pyramid?
How to invert the result of this for loop pyramid?

Time:10-22

Our professor wants us to perform our previous problem of inverting the result of a pyramid of numbers, given a certain height, but now using for loops. I seem to be doing something wrong with my code.

What I have so far:

size = int(input("Height: "))
for num in range(size, 0, -1):
    for num2 in range(1, num   1):
        print(num2, end=" ")

Output:

12345678
1234567
123456
12345
1234
123
12
1

Desired Output:

87654321
7654321
654321
54321
4321
321
21
1

Any help would be appreciated!

CodePudding user response:

you need to reverse your second for loop to achieve your the desired output. Try like this:

size = int(input("Height: "))
for num in range(size, 0, -1):
   for num2 in range(1, num   1)[::-1]:
      print(num2, end=" ")
    print("\n")

CodePudding user response:

You just need a descending range within a descending range.

This should do it:

height = int(input('Height: '))

for i in range(height, 0, -1):
    print(*map(str, range(i, 0, -1)))

Output:

Height: 8
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
  • Related