我几个月前开始学习编程,最近发现codechef http://codechef.com.
问题是,对于使用大量输入的问题,我的代码总是超出时间限制。我什至似乎无法做到输入测试 http://www.codechef.com/problems/INTEST work.
来自 codechef 的描述:
Input
输入以两个正整数 n k (n, k
Output
写入一个整数输出,表示有多少个整数 ti
可被 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)
我不确定我错过了什么。我怎样才能更快地处理这个问题?
这确实应该是一个评论,但无论如何。
请注意,有一个公认的 Python 2 解决方案here http://www.codechef.com/viewsolution/989892,运行时间为 45.77 秒,所以这显然是可能的。我认为你是 Python 3 缓慢 I/O 的受害者(看起来他们正在使用 3.1.2)。在一个 200 万行的输入文件(碰巧没有任何可整除的数字)上:当有很多数字时,没有太大区别),在修改为与 2 和 3 兼容的代码版本上,我得到:
~/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的(sum(not int(line) % t for line in sys.stdin[.buffer]))
混合:
~/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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)