与Python2相比,Python3中的代码相同

我编写了
this problem at CodeChef并将其作为Python3解决方案提交:

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) 

但是,如果我将代码编写为以下内容,它会超出时间限制,令我感到恐惧:

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 

并将其作为Python2解决方案提交,然后解决方案被接受.

我根本不明白这是怎么回事?…

==== ###更新### ====

Sebastian的解决方案适用于Python3,但比我的python2.7解决方案慢了10秒.我仍然没有得到答案,为什么与以前的语言相比,最新版本的语言会导致性能下降?…

最佳答案 我可以确认完全相同的解决方案通过python 2.7上的测试,但它在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是一个遍历行的迭代器.由于map是惰性的,代码支持大文件(不会立即使用整个文件).

以下代码传递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))

注意:它不支持任意大输入(以及问题中的代码).

点赞