Number pattern in python using the given code snippet

638 views Asked by At

Well the question might seem to be very easy i.e. to print a star pattern like

1
22
333
4444

For an input of 5

But the trick is that we have to make this pattern only by completing the following lines of code:

for i in range (1,input()):
    print {Here goes the code}

Code can not extend more than 2 lines

Link to the question

2

There are 2 answers

0
Martijn Pieters On BEST ANSWER

Numbers of the form x repeated y times are called repdigits. You can produce such a number simply by calculation. The challenge simplified this by asking you to produce repdigits where x == y; y repeats of the digit y.

You can produce a repeated 1, y times with the formula (10 ** y - 1) / 9; ten to the power y produces a 1 with y zeros. Subtract 1 and you have y nines. Divide that by 9 to get y ones:

>>> y = 7
>>> 10 ** y
10000000
>>> 10 ** y - 1
9999999
>>> (10 ** y - 1) // 9
1111111

Now all you have to do is multiply this by y to get y repeated y digits:

>>> y * (10 ** y - 1) // 9
7777777

Now you have a formula for producing a repdigit for any given y:

for y in range(1, input()):
    print(y * (10 ** y - 1) // 9)

No string operations needed; all that is needed is arithmetic operators.

Demo:

>>> sample = 5
>>> for y in range(1, 5):
...     print(y * (10 ** y - 1) // 9)
... 
1
22
333
4444
1
Yu Hao On

Use * for string repetition:

for i in range (1,input()):               # Use int(input()) in 3.x
    print(str(i) * i)