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?...
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With