【问题标题】:What are other options for faster io in Python 2.7Python 2.7 中更快的 io 的其他选项是什么
【发布时间】:2013-06-06 01:36:15
【问题描述】:

一段时间以来,我一直在为 codechef.com 上的 this 练习问题苦苦挣扎。我终于能够提出一个可行的解决方案。

import sys

def p():
    numbers, div = map(int,sys.stdin.readline().split())

    ans = 0
    for i in xrange(numbers):
        if int(sys.stdin.readline()) % div == 0:
            ans += 1
        i += 1

    print ans

p()

但这在 43.60 中执行,如 here 所示。它比给定的最佳解决方案差得多。他们都在使用不适用于 Python 2.7 的 psyco 模块。

在 Python 2.7 中是否有一些更快的 IO 方法可以提高这个实践问题的时间效率以及需要大量输入的一般编程问题?还请考虑可能会增加内存使用以获得所需时间效率的情况。

编辑:

这个问题不需要更快的浮点数 IO,但其他问题可能需要它,所以也为他们提出一些建议。

EDIT2:

nums = int(sys.stdin.readline())
float_nums = map(float,next(sys.stdin).split())
for p in islice(sys.stdin, float_nums, None):

我正在使用类似上面的东西来与@Martijn Pieters 一起使用浮点数的答案。我没有使用xrange()

【问题讨论】:

  • i += 1 完全是多余的,在这段代码中本质上是一个 noop。
  • 您可以尝试读取更大的输入块,然后将其分成几行。
  • @ThomasK 我是 Python 新手,所以任何提示都会很有用。
  • @Zel no-op 代表无操作。什么都不做,只是消耗一些时间的操作。
  • 当您浏览该站点上的解决方案时,您可以将 PsyCo 解决方案与其使用的超过 36 M 内存区分开来。

标签: python performance python-2.7


【解决方案1】:

将文件用作迭代器(不同的,可能更优化的缓冲策略),并利用生成器表达式:

import sys
from itertools import islice

def p():
    numbers, div = map(int, next(sys.stdin).split())
    print sum(int(l) % div == 0 for l in islice(sys.stdin, numbers))    

p()

这将布尔值视为整数(它们是子类;True 在整数上下文中为 1,False 为 0)。

或者试试:

import sys
from itertools import islice

def p():
    numbers, div = map(int, next(sys.stdin).split())
    print sum(1 for l in islice(sys.stdin, numbers) if int(l) % div == 0)    

p()

它们所做的工作量不同,并且根据存在的可整除数字的数量,一个可能比另一个更快(if 测试与求和 0 和 1)。

【讨论】:

  • sum(int(l) % div == 0 for l in islice(sys.stdin, numbers)) 可能会好一点(避免使用if
  • @Volatility 从简单的基准测试来看,使用if 似乎快了20-30%。请记住,在 python 中 if 不会花费太多,而添加数字会产生各种函数调用,因此会产生很多开销。最好分支并避免额外的加法调用,然后避免分支但始终执行加法。
  • 我错过了什么吗? if 在哪里?
  • @Zel:我改了答案;将在几秒钟内为您提供两种选择。
  • 对于浮点数,您需要一个公差级别来表示您想要接近 0 的程度。它会起作用,但您需要重新编写 == 0 测试。
【解决方案2】:

使用pypy,pysco 的继承者。

【讨论】:

  • 除了 CodeChef 不支持 PyPy。
  • @Martijn Pieters...哎呀,没想到。
猜你喜欢
  • 2013-07-04
  • 2011-02-26
  • 1970-01-01
  • 2016-09-26
  • 1970-01-01
  • 2014-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多