Daniel Chettiar
Daniel Chettiar

Reputation: 143

Cannot Print Out of For Loop

if __name__ == '__main__':

    N = int(input())
    list1 = []

    for data in range(N+1):
        commands, index, number = input().split()
            
        if commands == 'insert':
            list1.insert(int(index),int(number))
               
    print(list1) 

In this code whenever I try printing the list1 out of the for loop it doesn't print, neither does it give me any errors. It just displays EOF on the HackerRank website and in VS code it doesn't really give any output after I provide the Input

Does anyone know why?

Thanks for your time :)

HackerRank outputVSS code Output

Upvotes: 0

Views: 379

Answers (2)

Krishna Chaurasia
Krishna Chaurasia

Reputation: 9552

You are iterating the loop one extra time by using range(N+1) so the process is waiting for one more input and it times out after some time.

Change the code to as below:

if __name__ == '__main__':

    N = int(input())
    list1 = []

    for data in range(N):
        commands, index, number = input().split()
            
        if commands == 'insert':
            list1.insert(int(index),int(number))
               
    print(list1) 

Upvotes: 2

rdas
rdas

Reputation: 21275

If the input is 3, then N+1 is 4.

range(N+1) would then be range(4). Which is 0, 1, 2, 3 - 4 items.

i.e. The loop runs 4 times. But there is only 3 lines of input on stdin.

That's what the error is telling you. It was expecting some input but it got EOF - End of File.

You should just use range(N) or range(1, N+1) - which will cause the loop to run 3 times.

if __name__ == '__main__':

    N = int(input())
    list1 = []

    for _ in range(N):
        commands, index, number = input().split()
            
        if commands == 'insert':
            list1.insert(int(index),int(number))
               
    print(list1) 

Upvotes: 1

Related Questions