简体   繁体   中英

Improving the speed of a Python solution to the Lead Game exercise

Here is my solution to the Lead Game problem on Codechef . It runs fine, but took 2.63 sec and 3.8M memory, while I saw many C programs that had completed in 0.08 seconds and 1.6M memory. How can I make it faster?

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

I wouldn't worry about the memory footprint (Python data structures take a little more space, and it's normal) and also it's hard to expect a Python script to beat a C program in terms of speed.

Edit : no need to keep leads history

My O(n) algorithm ran in 1.18 seconds:

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]

Edit

To see where your algorithm spends most time you can use:

cat inputfile | python -m cProfile yourScript.py

Quick inspiration looks that you have O(n^2) algorithm, where you could use O(n) algorithm.

Instead of

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

Just assemble one or multiple for loops (but not nested for loops).

It is not problem, that python si too slow, just your algorithm is not efficient enough

EDIT

I was wrong, maybe append is just too slow. Try using comprehension

so diff is just (out of for loop)

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

and use try to use tuples:

code is then.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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