Reputation: 1295
I coded this problem at CodeChef and submitted it as Python3 solution:
import sys
n,k = map(int,sys.stdin.readline().split(" "))
nos = map(int,sys.stdin.readlines())
ans = 0
for i in nos:
if i>0 and i%k == 0:
ans += 1
print(ans)
But it gives you a Time Limit Exceeded, to my horror, if I write the code as:
import sys
n,k = map(int,sys.stdin.readline().split(" "))
nos = map(int,sys.stdin.readlines())
ans = 0
for i in nos:
if i>0 and i%k == 0:
ans += 1
print ans
and submit it as a Python2 solution, then the solution gets accepted.
I simply fail to understand where is this going?...
====### UPDATE ###====
solution by Sebastian works for Python3 but is a considerable 10secs slower than my python2.7 solution. I still did not get the answer that why is there a degradation of performance with latest version of the language compared to previous?...
Upvotes: 5
Views: 1848
Reputation: 414215
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 import map # enable lazy map on Python 2.7
except ImportError:
pass
file = sys.stdin
n, k = map(int, next(file).split())
print(sum(1 for i in map(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(1 for i in numbers if i % k == 0))
Note: it doesn't support arbitrary large inputs (as well as your code in the question).
Upvotes: 2
Reputation: 6657
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
Upvotes: 0
Reputation: 1667
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]
Upvotes: 0