Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same code slower in Python3 as compared to Python2

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?...

like image 360
whizzzkid Avatar asked Nov 04 '22 04:11

whizzzkid


1 Answers

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).

like image 51
jfs Avatar answered Nov 08 '22 10:11

jfs