Python 2.7 中更快的 io 有哪些其他选项? [英] What are other options for faster io in Python 2.7

查看:35
本文介绍了Python 2.7 中更快的 io 有哪些其他选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been struggling with this practice problem on codechef.com for some time. I was finally able to make a working solution.

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 中执行,如此处所示.这比给定的最佳解决方案要糟糕得多.他们都使用了不适用于 Python 2.7 的 psyco 模块.

But this executed in 43.60 as is shown here. It is much worse than the best given solutions. They are all using psyco module which is not working for Python 2.7.

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

Is there some faster method of IO in Python 2.7 which can improve the time-efficiency of this practice problem and in general programming problems requiring huge inputs? Please also consider the cases when memory use may be increased for getting desired time-efficiency.

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

Faster IO for floating point numbers is not required for this problem but it may be required for some other problem so suggest something for them also.

编辑 2:

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 was using something like the above for use with @Martijn Pieters answer for floating point numbers. I am not using xrange()

推荐答案

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

Use the file as an iterator (different, potentially more optimal buffer strategy), and take advantage of generator expressions:

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

This treats booleans as integers (they are a subclass; True is 1 in an integer context, False is 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 相加).

These do different amounts of work, and depending on the amount of divisible numbers present, one could be faster than the other (if tests versus summing 0s and 1s).

这篇关于Python 2.7 中更快的 io 有哪些其他选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆