Reputation: 97
Like those programming challenges, right now I do the following:
For a single variable:
x = int(sys.stdin.readline())
for many variables
A, B, C = map(int,sys.stdin.readline().split())
Is this optimal or are there faster ways?
Upvotes: 2
Views: 3922
Reputation: 8740
Python's sys library has 2 file objects stdin and stdout connected with STDIN and STOUT. stdin file object has readline() and readlines() methods & stdout file object has write() method. We can use these methods for fast I/O in Python.
visit here
Upvotes: 0
Reputation: 67063
If you have numpy available, the numpy loading functions are very fast. For example:
>>> import numpy
>>> s = '1\n2\n3\n4\n'
>>> data = numpy.fromstring(s, dtype=int, sep='\n')
>>> data
array([1, 2, 3, 4])
This example loads from a string, but you can also load directly from an open file using numpy.fromfile.
Upvotes: 1