Home > Blockchain >  Python input() does not read whole input data
Python input() does not read whole input data

Time:03-14

I'm trying to read the data from stdin, actually I'm using Ctrl C, Ctrl V to pass the values into cmd, but it stops the process at some point. It's always the same point. The input file is .in type, formating is that the first row is one number and next 3 rows contains the set of numbers separated with space. I'm using Python 3.9.9. Also this problem occurs with longer files (number of elements in sets > 10000), with short input everything is fine. It seems like the memory just run out. I had following aproach:

def readData():
# Read input
for line in range(5):
    x = list(map(int, input().rsplit()))
    if(line == 0):
        nodes_num = x[0]
    if(line == 1):
        masses_list = x
    if(line == 2):
        init_seq_list = x
    if(line == 3):
        fin_seq_list = x

return nodes_num, masses_list, init_seq_list, fin_seq_list

and the data which works:

6
2400 2000 1200 2400 1600 4000
1 4 5 3 6 2 
5 3 2 4 6 1

and the long input file: https://pastebin.com/atAcygkk it stops at the sequence: ... 2421 1139 322], so it's like a part of 4th row.

CodePudding user response:

To read input from "standard input", you just need to use the stdin stream. Since your data is all on lines you can just read until the EOL delimiter, not having to track lines yourself with some index number. This code will work when run as python3.9 sowholeinput.py < atAcygkk.txt, or cat atAcygkk.txt| python3.9 sowholeinput.py.

def read_data():
    stream = sys.stdin
    num = int(stream.readline())
    masses = [int(t) for t in stream.readline().split()]
    init_seq = [int(t) for t in stream.readline().split()]
    fin_seq = [int(t) for t in stream.readline().split()]
    return num, masses, init_seq, fin_seq

Interestingly, it does not work, as you describe, when pasting the text using the terminal cut-and-paste. This implies a limitation with that method, not Python itself.

  • Related