python input() function cuts off really long inputs

65 Views Asked by At

I'm writing a solution to a programming challenge and I was getting the answer wrong, but only for really long inputs. The issue doesn't appear to be my algorithm, but that the python input function cuts off characters after reaching a certain length (2^14 or just shy of 16,384 characters). I am copying and pasting the 26,000+ character input from a file to the console and the entire input appears when I paste it, but when I print it only the first 16,381 characters are read.

The challenge provides 2 inputs that are each over 26,000 characters in length. The input function only gets the first 16,000-ish before cutting off the rest. Doing a 2nd input() doesn't get the remaining characters but gets the next input instead.

In the competition, I have no control over how the data is provided - it's provided as console input so file reading won't work unless there's some way to make file reading read from the console stream.

How do I retrieve really long inputs without installing any additional python libraries? Is there something that would allow me to read the inputs as individual words similar to the java Scanner's next() function? I don't need to save the entire input, I only need to process the whole thing character for character and do some math with it, but I can't do that if I can only pull 60% of the input.

line = input()
print(len(line))

Providing the above code with a single 26,000+ character input (copy and pasted from somewhere), and the printed result is 16,381 characters long.

2

There are 2 best solutions below

0
SIGHUP On

Your data almost certainly includes one (or more) newline characters.

input() reads up to and excluding the first newline character.

You can read data from the standard input stream as follows:

import sys

data = sys.stdin.read()
print(len(data))

Consuming the input in this way is impervious to newline characters - i.e., it stops at EOF

Note:

This technique is not well-suited to interactive input

0
Judson Birkel On

To be clear, the 26,000 characters long input was a single input with 0 new lines (again, this was based on a competition challenge problem and the data in the problem set was huge).

I did, however, find out the issue actually had to do with the IDE I was using. I was using an executable (not installed) version of VSCode. When running the program in VSCode, the input() function was truncated @ a little over 16,000 characters. When running the same program in Idle, no such truncation occurred and I was able to get the correct answers on the remainder of my program.