Home > Mobile >  space tower in python with loops
space tower in python with loops

Time:01-27

1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8     8 7 6 5 4 3 2 1
1 2 3 4 5 6 7         7 6 5 4 3 2 1
1 2 3 4 5 6             6 5 4 3 2 1
1 2 3 4 5                 5 4 3 2 1
1 2 3 4                     4 3 2 1
1 2 3                         3 2 1
1 2                             2 1
1                                 1

How can I code this in python?

So far this is my code but I can't figure out the spaces.

number = int(input("enter a number to create your triangle: "))

for col in range(number,0,-1):
    for row in range(1,col):
        print(row,  end=" ")

    if col<number:
        print(" "*(row*2), end="")
        
    for row in range(col-1,0,-1):
        print(row, end=" ")
    print()

CodePudding user response:

Instead of looping multiple times, you could create a base list containing all numbers as strings, iterate once to print each row and the reverse:

number = 9

base = [str(n) for n in range(1, number 1)]
for i, idx in enumerate(range(len(base)-1, 0, -1)):
    if i == 0:
        print(' '.join(base   base[::-1]))
    base[idx] = ' '
    print(' '.join(base   base[::-1]))

Out:

1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8     8 7 6 5 4 3 2 1
1 2 3 4 5 6 7         7 6 5 4 3 2 1
1 2 3 4 5 6             6 5 4 3 2 1
1 2 3 4 5                 5 4 3 2 1
1 2 3 4                     4 3 2 1
1 2 3                         3 2 1
1 2                             2 1
1                                 1

CodePudding user response:

As I've pointed in this comment, using all "power" of print() and unpacking you can make it really easy.

By default all arguments passed to print() will be separated with space, so we can just unpack there range from 1 to current index, string of spaces and reverse range from current index to 1:

number = int(input("enter a number to create your triangle: "))

for i, n in enumerate(range(number, 0, -1)):
    print(*range(1, n   1), *(" " * (i * 2)), *range(n, 0, -1))

Output:

1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8     8 7 6 5 4 3 2 1
1 2 3 4 5 6 7         7 6 5 4 3 2 1
1 2 3 4 5 6             6 5 4 3 2 1
1 2 3 4 5                 5 4 3 2 1
1 2 3 4                     4 3 2 1
1 2 3                         3 2 1
1 2                             2 1
1                                 1

Important notice: Code above will work properly only for number below 10.

  • Related