Same Code Slower In Python3 As Compared To Python2
Solution 1:
I can confirm that exactly the same solution passes the tests on python 2.7, but it timeouts on python 3.1:
import sys
try:
from future_builtins importmap# enable lazy map on Python 2.7except ImportError:
pass
file = sys.stdin
n, k = map(int, next(file).split())
print(sum(1for i inmap(int, file) if i % k == 0))
file
is an iterator over lines. The code supports large files due to map
is lazy (doesn't consume the whole file at once).
The following code passes the tests on python 3.1:
import sys
n, k, *numbers = map(int, sys.stdin.buffer.read().split())
print(sum(1for i in numbers if i % k == 0))
Note: it doesn't support arbitrary large inputs (as well as your code in the question).
Solution 2:
In python3, things like map
, zip
return generators instead of a list. I think the generator brings the overhead that make your code TLE. To make a real list, use list comprehension [int(line) for line in std.sys]
Solution 3:
The error occurs the line that says, n,k = map(int,sys.stdin.readline().split(" "))
. I tried to separate the n
and the k
, but it still seems to get stuck as soon as the map
command is called. Here is a page that explains the map
function: http://docs.python.org/2/library/functions.html#map Something seems strange with the syntax that neither I or IDLE could find. Hope this helps
Post a Comment for "Same Code Slower In Python3 As Compared To Python2"