S
S
savados2011-06-24 12:57:46
Python
savados, 2011-06-24 12:57:46

Fastest way to read stdin in Python?

Hello.
The input is the following data:
2
3 3
1 2
2 3
1 3
4 2
1 2
3 4
The first line is the number of test cases. The first line of each case contains two numbers separated by a space: how many different elements and how many pairs of these elements will be displayed now. Then the couples come out. Here is a link to the problem just in case: www.spoj.pl/problems/BUGLIFE/
I need to turn each test case into a list of pairs and send it to the solve function. That is, I have to send to solve in turn [(1, 2), (2, 3), (1, 3)] and [(1, 2), (3, 4)]
Usually I do this naively (before that input has never been a bottleneck)

def main(raw_input=raw_input):
  cases = int(raw_input())
  for case in xrange(cases):
    pairs = []
    tmp = raw_input().split()
    for i in range(int(tmp[1])) :
      pr = raw_input().split()
      pairs.append((int(pr[0]), int(pr[1])))
    print 'Scenario #%d:' % (case + 1)
    solve(pairs)
* This source code was highlighted with Source Code Highlighter .

But here the task turned out to have draconian time requirements, I launched the profiler, it turned out that the solve function itself is almost imperceptible, but input processing eats up all the time. I know that it is possible to read more efficiently, but I would like to immediately fill this gap in knowledge in the most optimal way. :-) If there is a generator instead of a list of pairs, only better.
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim Avanov, 2011-06-24
@savados

raw_input is used for interactive input.
Most likely you need to use sys.stdin.read(), or sys.stdin.readlines(), or iteratively through a generator (for line in sys.stdin).

S
sdfsdhgjkbmnmxc, 2011-06-27
@sdfsdhgjkbmnmxc

I would do like this:

sys.stdin.next() # skip first line
pairs = [map(int, line.split()[:2]) for line in sys.stdin]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question