繁体   English   中英

提高针对领先游戏练习的Python解决方案的速度

[英]Improving the speed of a Python solution to the Lead Game exercise

这是我对Codechef上的Lead Game问题的解决方案。 它运行良好,但是花费了2.63秒和3.8M的内存,而我看到许多C程序在0.08秒和1.6M的内存中完成了。 我怎样才能使其更快?

import sys
cnt = int(sys.stdin.readline())
match = [[int(x) for x in sys.stdin.readline().split()] for i in range(cnt)]
diff=[]
for i in range(cnt):
      if i!=0:
             match[i]=[sum(vals) for vals in zip(match[i-1],match[i])]
      diff.append([1 if max(match[i])==match[i][0] else 2,abs(match[i][0]-match[i][1])])
maxval = max(diff,key=lambda x:x[1])
sys.stdout.write(str(maxval[0]) + ' ' + str(maxval[1]))  

我不会担心内存占用(Python数据结构占用更多空间,这是正常的),而且很难期望Python脚本在速度方面能胜过C程序。

编辑 :无需保留销售线索历史记录

我的O(n)算法运行了1.18秒:

import sys

rounds = int(sys.stdin.readline())

score = [0,0]
leads = [0,0]
while rounds > 0:
    results = map(int, sys.stdin.readline().split())
    score[0] += results[0]
    score[1] += results[1]
    lead = score[0] - score[1]
    if (lead < 0 and leads[1] < -lead): leads[1] = -lead
    if (lead > 0 and leads[0] < lead): leads[0] = lead
    rounds -= 1

if (leads[0] > leads[1]): print 1, leads[0]
else: print 2, leads[1]

编辑

要查看算法花费最多时间的地方,可以使用:

cat inputfile | python -m cProfile yourScript.py

快速灵感显示您拥有O(n ^ 2)算法,可以在其中使用O(n)算法。

代替

 for:
    for: #this for  comes from line whit list comprehension

只需汇编一个或多个for循环(但不嵌套for循环)。

没问题,python si太慢了,只是您的算法不够高效

编辑

我错了,也许添加太慢了。 尝试使用理解

所以差异只是(出于循环)

diff = [[1 if max(m)==m[0] else 2,abs(m[0]-m[1])] for m in match]

并尝试使用元组:

然后是代码。

import sys
cnt = int(sys.stdin.readline())
match = [tuple(int(x) for x in sys.stdin.readline().split()) for i in range(cnt)]
diff=[]
for i in range(cnt):
   if i!=0:
         match[i]=tuple(sum(vals) for vals in zip(match[i-1],match[i]))
diff = [tuple((1 if max(m)==m[0] else 2,abs(m[0]-m[1]))) for m in match]
maxval = max(diff,key=lambda x:x[1])
sys.stdout.write(str(maxval[0]) + ' ' + str(maxval[1])) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM