'Print a numerical triangle [duplicate]
You are given a positive integer (example: N = 6). Print a numerical triangle of height like the one below:
1
22
333
4444
55555
Use no more than two lines of code. Use a for loop and print function only. You can't use anything related to strings. N is an input.
What I tried:
for i in range(1,int(input())):
print(*range(1, i+1))
my output:
1
1 2
1 2 3
1 2 3 4
Solution 1:[1]
One way to get the triangle indicated (without using strings) is to treat the output as numbers and to calculate those numbers:
N = 6
for i in range(1, N):
print(sum(10**j for j in range(i)) * i)
Output as requested.
Solution 2:[2]
You can use list multiplication, list unpacking and print's capability of taking multiple arguments and outputting them separated by sep to produce the correct output:
for i in range(1, int(input())):
l = [i] * i
print(*l, sep="")
Or on two lines:
for i in range(1, int(input())):
print(*[i] * i, sep="")
Solution 3:[3]
Tell whoever left this assignment you did it in one line and no strings used:
be careful what you wish for
_ = [print((10**i - 1)//9 * i) for i in range(1, 6)]
if you hate math:
_ = [[print(i, end='' if j != i-1 else '\n') for j in range(i)] for i in range(1, 6)]
Personally I prefer this one for this assignment:
_ = [print(i*int(bin((1 << i) - 1)[2:])) for i in range(1, 6)]
Solution 4:[4]
You can use
for i in range(1,int(input())):
print(str(i)*i)
Solution 5:[5]
This will help you.
edit: Now without using string function.
n = 6 # write you value here.
for a in range(1,n):
print(f'{a}'*a)
Solution 6:[6]
Your code must be
for i in range(1, int(input())+1):
print(*[i for j in range(i)])
Solution 7:[7]
Here is one function that works.
def f(n): a='' for i in range(1,n): a=a+'1' print(i*int(a))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | quamrana |
| Solution 2 | Programmer |
| Solution 3 | |
| Solution 4 | |
| Solution 5 | |
| Solution 6 | |
| Solution 7 | Perception Nuevo |
