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


here solution the lead game problem on codechef. runs fine, took 2.63 sec , 3.8m memory, while saw many c programs had completed in 0.08 seconds , 1.6m memory. how can make faster?

import sys cnt = int(sys.stdin.readline()) match = [[int(x) x in sys.stdin.readline().split()] in range(cnt)] diff=[] in range(cnt):       if i!=0:              match[i]=[sum(vals) 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 memory footprint (python data structures take little more space, , it's normal) , it's hard expect python script beat c program in terms of speed.

edit: no need 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 , leads[1] < -lead): leads[1] = -lead     if (lead > 0 , 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 algorithm spends time can use:

cat inputfile | python -m cprofile yourscript.py 

Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -