Reputation: 129
I am trying to get this output (with comas):
1
2, 1
3, 2, 1
4, 3, 2, 1
5, 4, 3, 2, 1
The problem is, i am not able to "remove" the last coma (,) situated next to the number 1 on each line. Here is the code:
for i in range(1,6):
for x in range(i,0,-1):
print("%i,"%(x), end=" ")
print()
Upvotes: 1
Views: 506
Reputation: 48057
You may achieve it via using str.join
with range
and map
:
>>> n = 5
>>> for i in range(n):
... print(', '.join(map(str, range(i+1, 0, -1))))
...
1
2, 1
3, 2, 1
4, 3, 2, 1
5, 4, 3, 2, 1
If you are looking for one liner solution, then you may write it using nested str.join
as:
>>> print('\n'.join(', '.join(map(str, range(i+1, 0, -1))) for i in range(n)))
1
2, 1
3, 2, 1
4, 3, 2, 1
5, 4, 3, 2, 1
where n
is the count of number of lines needed to be printed.
Upvotes: 1
Reputation: 4528
Just try output last element after for
loop:
for i in range(1,6):
for x in range(i,1,-1):
print("%i,"%(x), end=" ")
print("1", end=" ")
print()
#1
#2, 1
#3, 2, 1
#4, 3, 2, 1
#5, 4, 3, 2, 1
Upvotes: 0