Home > Back-end >  How to print an inverted triangle, sorted right?
How to print an inverted triangle, sorted right?

Time:07-08

***
 **
  *

This is what I'm trying to get python to print. The conditions are the following: 1. must use nested loops or more.

I've solved this with the following code:

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

However, I'm trying to see if I can get the same output without declaring the 'n' variable. Is there a way to do this?

CodePudding user response:

You could take advantage of str.rjust() like this:

WIDTH = 3

stars = '*' * WIDTH

print('\n'.join(stars[i:].rjust(WIDTH) for i in range(WIDTH)))

Output:

***
 **
  *

CodePudding user response:

I've solved this with the following:

for i in range(3): 
  for j in range(i):
   print(' ', end = '')
  for j in range(3-i): 
    print('*', end='')
  print()

CodePudding user response:

def printTriangle(columns:int):
    return "".join([" "*space "*"*(columns-space) "\n" for space in range(1 columns)])
    
print(printTriangle(5))

>>> *****
>>>  ****
>>>   ***
>>>    **
>>>     *
  • Related