Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hackerrank Quest -- bug or misunderstanding? [duplicate]

Tags:

python

I was playing with Hackerrank and came across this problem.

It is written as:

You are given a positive integer N. You have to print a numerical triangle of height N−1 as shown below:

1
22
333
4444
55555
......

My immediate thought was this solution:

for i in range(1,input()):
    print(str(i)*i)

Which outputs this given (5) as the first line of input:

1
22
333
4444

The submission says it's not right. Other suggestions that were accepted are much less elegant in my mind:

for i in range(1,int(input())):
    print((10**i)//9*i)

This outputs:

1
22
333
4444

The output is identical but the code is ugly. Why is this solution acceptable and not mine?

like image 988
David S. Avatar asked Mar 02 '26 02:03

David S.


1 Answers

You missed something in the description:

Note Using anything related to strings will give a score of 0.

You are using str() in your solution, so it is invalid according to the rules of the challenge. The point is to find that trick with calculating the number rather than build it from a string.

I used:

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

to pass the challenge, which is fundamentally the same approach. You make use of the fact that 10 // 9 is 1, 100 // 9 is 11, 1000 // 9 is 111, etc.; get yourself enough zeros to produce the right number of digits, and multiply the repeating 1 number with i to get a number of repeated i digits.

like image 194
Martijn Pieters Avatar answered Mar 07 '26 09:03

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!