中的相同代码速度较慢

中的相同代码速度较慢

本文介绍了与 Python2 相比,Python3 中的相同代码速度较慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 CodeChef 编写了这个问题 并将其作为 Python3 解决方案提交:

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

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

and submit it as a Python2 solution, then the solution gets accepted.

我只是不明白这是怎么回事?...

I simply fail to understand where is this going?...

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

====### UPDATE ###====

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

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

推荐答案

我可以确认完全相同的解决方案通过了 python 2.7 的测试,但它在 python 3.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 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 是惰性的(不会一次消耗整个文件).

file is an iterator over lines. The code supports large files due to map is lazy (doesn't consume the whole file at once).

以下代码在 python 3.1 上通过了测试:

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

这篇关于与 Python2 相比,Python3 中的相同代码速度较慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 06:21