stevenhalim / cpbook-code

CP4 Free Source Code Project (C++17, Java11, Python3 and OCaml)
2k stars 493 forks source link

StopIteration Error for IO_in1 #83

Open drmingle opened 3 years ago

drmingle commented 3 years ago

I tried to run this code and received a StopIteration error.

# IO_in1.txt
import sys
inputs = iter(sys.stdin.readlines())
TC = int(next(inputs))
for _ in range(TC):
    print(sum(map(int, next(inputs).split())))

Can you tell me how to prevent this traceback?

---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-221-4615b4523133> in <module>
      1 import sys
      2 inputs = iter(sys.stdin.readlines())
----> 3 TC = int(next(inputs))
      4 for _ in range(TC):
      5     print(sum(map(int, next(inputs).split())))

StopIteration: 
stevenhalim commented 3 years ago

Hi Damian,

When you feed input to the Python interpreter, use the EOF symbol CTRL+D (on Windows) or CTRL+Z? (on Linux/Mac - I am not sure) after the last line of input. Because

inputs = iter(sys.stdin.readlines())

reads all input at one go.

Alternatively, use command line IO redirection like this

python IO.py < IO_in1.txt

Regards,

Steven Halim (Dr.) Senior Lecturer School of Computing, National University of Singapore http://www.comp.nus.edu.sg/~stevenha IOI 2020 (https://ioi2020.sg/) and 2021 (http://ioi2021.sg/) Deputy Director+IC Member https://visualgo.net and https://cpbook.net (CP4 is out)

On Tue, Dec 29, 2020 at 1:04 PM Damian Mingle notifications@github.com wrote:

I tried to run this code and received a StopIteration error.

IO_in1.txt

import sys inputs = iter(sys.stdin.readlines()) TC = int(next(inputs)) for _ in range(TC): print(sum(map(int, next(inputs).split())))

Can you tell me how to prevent this traceback?


StopIteration Traceback (most recent call last)

in 1 import sys 2 inputs = iter(sys.stdin.readlines()) ----> 3 TC = int(next(inputs)) 4 for _ in range(TC): 5 print(sum(map(int, next(inputs).split()))) StopIteration: — You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub , or unsubscribe .