Is there a faster way to input input in python?

In coding competitions, we are faced with inputs such as:

2 3 4 5 

So we do the following:

 m, n = [int(x) for x in raw_input().split(' ')] 

Is there a faster way to do the same?

+4
source share
2 answers

For all practical purposes, it is about as fast as you can get. On some machines, you can see acceleration by an order of magnitude or a couple of percent if you switch from map instead of understanding the list, but this is not guaranteed.

Here are some quick timings on my machine:

 from itertools import imap #map >>> timeit.timeit('x,y = map(int,line.split(" "))','from __main__ import line') 4.7857139110565186 >>> timeit.timeit('x,y = map(int,line.split())','from __main__ import line') 4.5680718421936035 #list comprehension >>> timeit.timeit('x,y = [int(x) for x in line.split(" ")]','from __main__ import line') 4.3816750049591064 >>> timeit.timeit('x,y = [int(x) for x in line.split()]','from __main__ import line') 4.3246541023254395 #itertools.imap >>> timeit.timeit('x,y = imap(int,line.split(" "))','from __main__ import line,imap') 4.431504011154175 >>> timeit.timeit('x,y = imap(int,line.split())','from __main__ import line,imap') 4.3257410526275635 #generator expression >>> timeit.timeit('x,y = (int(x) for x in line.split(" "))','from __main__ import line') 4.897794961929321 >>> timeit.timeit('x,y = (int(x) for x in line.split())','from __main__ import line') 4.732620000839233 

Surprisingly, split() seems better than split(" ") .


If you are guaranteed to have ascii digits from 0 to 9, you can make a good bit better by using ord :

 >>>timeit.timeit('x,y = [ord(x)-48 for x in line.split(" ")]','from __main__ import line') 1.377655029296875 >>> timeit.timeit('x,y = [ord(x)-48 for x in line.split()]','from __main__ import line') 1.3243558406829834 

But this imposes serious restrictions on your entries.


Another idea you could try (I have no idea what the performance implications will be), but you can read your lines from sys.stdin :

 import sys for line in sys.stdin: x,y = [ord(x)-48 for x in line.split()] 
+7
source

Use map() , this is faster than understanding lists when used with built-in functions:

 m, n = map(int, raw_input().split()) 
+1
source

Source: https://habr.com/ru/post/1438435/


All Articles