简体   繁体   中英

how to use sys.stdin.readline()?

I am using the jupyter notebook now. When I try to run the code below, it doesn't work from the third line.

Error message : "invalid literal for int() with base 10: ''.

I can't find any problem at third line. I want to use sys module than input() to reduce the running time.

from sys import stdin
qu=[]
for _ in range(int(stdin.readline())):
    arr = stdin.readline().split()
    if arr[0] == 'push':
        qu.append(arr[1])
    elif arr[0] == 'pop':
        if qu: print(qu.pop(0))
        else: print(-1)
    elif arr[0] == 'size':
        print(len(qu))
    elif arr[0] == 'empty':
        print(1-int(bool(qu)))
    elif arr[0] == 'front':
        if qu: print(qu[0])
        else: print(-1)
    elif arr[0] == 'back':
        if qu: print(qu[-1])
        else: print(-1)
    else:
        pass

ValueError Traceback (most recent call last) in 1 from sys import stdin 2 qu=[] ---->3 for _ in range(int(stdin.readline())): 4 arr = stdin.readline().split() 5 if arr[0] == 'push':

ValueError: invalid literal for int() with base 10: ''

you are reading a line and converting it to int. If you enter more than 1 number, it will throw exception because you are not splitting it.Use for _ in range(int(stdin.readline().split()[0])): if you want just first number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM