[Tutor] How to speed up input/string parsing ...

Aditya Lal aditya.n.lal at gmail.com
Thu Sep 27 09:36:17 CEST 2007


Hi !!
I was trying to solve SPOJ (www.spoj.pl) problems - ADDREV (add reversed
numbers).

My solution clocked 0.58 seconds in SPOJ's computer as compared to best time
of 0.28. Interestingly my program spends 50% of its total execution time in
reading/parsing the input.

Following is the sample input/output. The actual data set contains ~ 10,000
numbers.

Sample input:

3  --> indicates the # of lines to follow
24 1      --> 2 numbers separated by a space
4358 754
305 794


Sample output:

34  --> reverse of sum of reverse of both numbers
1998
1

I wrote the following code -

def rev(n) :
    m = 0
    while n > 0 :
        m = m*10 + n%10
        n = n/10
    return m

def solve(line) :
    nums = line.split(' ')
    a = int(nums[0])
    b = int(nums[1])
    return rev( rev(a) + rev(b) )

if __name__ == '__main__' :

    N = int(sys.stdin.readline())
    lines = sys.stdin.readlines()
    for i in xrange(N) :
        print solve(lines[i])

My Question :

How do I improve the input reading or string parsing ? I know there should
be a better way because the best program (at cost of memory) performs > 50%
faster than mine. So he must have done something to improve input
processing.

Thanks
Aditya
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070927/981585af/attachment.htm 


More information about the Tutor mailing list