1

I am trying to solve Kattis problem. The full problem is found in the link: https://open.kattis.com/problems/addingwords

The part of the problem that I'm confused with is : "Input is a sequence of up to 2000 commands, one per line, ending at end of file."

What would be the code for this input? I tried doing this:

import sys

for line in sys.stdin.readlines():
    #print('something')

After this, I continued the program as normal within the indentation from above. My question is, how would I test whether the program is working in cmd? I want to test a few cases, but when I input something, the command prompt keeps waiting for other results instead of printing anything out. And when I press control C the program ends abruptly. How are we supposed to check whether the program is working while taking in user input till end of file?

Naya Keto
  • 123
  • 3
  • 8

1 Answers1

3

The problem here is that readlines() is eager not lazy. That means it will read the entire file into memory (until EOF) and then split it into lines and return a list of those lines. So when working with interactive stdin, sys.stdin.readline() will wait until the end of stdin (Ctrl-D on linux/macOS, Ctrl+Z on windows).

But there is no need for readlines() (and in fact, you almost should never use it). Iterating over a file object by default does so by lines:

for line in sys.stdin:
    print('got line!')

The docs even admit that you should do this. If you do need all lines in a list, then just do list(sys.stdin).

Bailey Parker
  • 15,599
  • 5
  • 53
  • 91