处理python中的大型输入 [英] Handling large inputs in python

查看:128
本文介绍了处理python中的大型输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几个月前我开始学习编程,最近才发现 codechef

问题是对于使用大量输入的问题我的代码alwaqys超出时间限制。我甚至无法使输入测试工作。

I started learning programming a few months ago and just recently found codechef.
The problem is that on problems that use large amounts of input my code alwaqys exceehe time limit. I can't even seem to make the input test work.

来自codechef的说明:

Description from codechef:


输入

Input

输入以两个正整数nk(n,k <= 10 ^ 7)开始。下一个
n输入行包含一个正整数ti,每个不大于
10 ^ 9。

The input begins with two positive integers n k (n, k<=10^7). The next n lines of input contain one positive integer ti, not greater than 10^9, each.

输出


写一个整数输出,表示有多少整数ti是
可被k整除。

Write a single integer to output, denoting how many integers ti are divisible by k.

这是代码:

n, t = [int(x) for x in input().split()]
c = 0
for i in range(n):
    if not int(input()) % t:
        c += 1
print(c)

我不确定我错过了什么。我怎样才能更快地处理这个?

I'm not sure what I'm missing. How can I handle this faster?

推荐答案

这应该是一个评论,但无论如何。

This should really be a comment, but anyway.

请注意,此处有一个可接受的Python 2解决方案,运行时为45.77s ,所以它显然是可能的。我认为你是Python 3缓慢I / O的受害者(看起来他们正在使用3.1.2)。在一个200万行输入文件(它没有任何可分割的数字):当有很多时没有太大区别),在你的代码版本修改为与2和3兼容时,我得到:

Note that there's an accepted Python 2 solution here, with runtime 45.77s, so it's clearly possible. I think you're a victim of Python 3's slow I/O (looks like they're using 3.1.2). On a two million line input file (which happens not to have any numbers which are divisible): there's not much difference when there are a lot), on a version of your code modified to be compatible with 2 and 3, I get:

~/coding$ time python2.6 enormread.py < sample.txt 
0

real    0m3.971s
user    0m3.712s
sys 0m0.256s
~/coding$ time python2.7 enormread.py < sample.txt 
0

real    0m2.637s
user    0m2.428s
sys 0m0.204s
~/coding$ time python3.2 enormread.py < sample.txt 
0

real    0m10.412s
user    0m10.065s
sys 0m0.344s
~/coding$ time ~/sys/Python-3.3.0a2/python enormread.py < sample.txt 
0

real    0m6.776s
user    0m6.336s
sys 0m0.436s
~/coding$ time pypy enormread.py < sample.txt 
0

real    0m2.211s
user    0m1.948s
sys 0m0.028s

抛出@ agf的(对于sys.stdin [.buffer]中的行,总和(不是int(行)%t))进入组合:

To throw @agf's (sum(not int(line) % t for line in sys.stdin[.buffer])) into the mix:

~/coding$ time python2.7 enormfast.py < sample.txt 
0

real    0m1.454s
user    0m1.436s
sys 0m0.016s
~/coding$ time python3.2 enormfast.py < sample.txt 
0

real    0m2.243s
user    0m2.228s
sys 0m0.012s

这篇关于处理python中的大型输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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