I'm a beginner Python (2.7) programmer, and I've just started solving basic problems on SPOJ. I correctly solved the ADDREV problem (http://www.spoj.com/problems/ADDREV/), however my code takes 0.06s time and 8.8M memory to run. The top Python 2.7 rankers for the problem take <0.005s and 4.00M. Since I am starting out and this is a simple code snippet, I would love to get specific tips on how I can optimise the code below to reach these levels of efficiency. I am reading popularly available tips to optimise Python code, including the use of profilers, however I would really appreciate any tips I can already get here.
The problem as described there:
Input
The input consists of N cases (equal to about 10000). The first line of the input contains only positive integer N. Then follow the cases. Each case consists of exactly one line with two positive integers separated by space. These are the reversed numbers you are to add.
Output
For each case, print exactly one line containing only one integer - the reversed sum of two reversed numbers. Omit any leading zeros in the output.
(Source: http://www.spoj.com/problems/ADDREV/)
Here's the code:
def reverse(num): # Takes a string as input and reverses it, removing any leading or trailing zeros
num = num.strip("0")
return num[::-1]
num_cases = input()
for i in range(0, num_cases):
usr_input = raw_input()
arr = usr_input.split()
reversed_sum = int(reverse(arr[0])) + int(reverse(arr[1]))
print reverse(str(reversed_sum))
xrange(..)
instead ofrange(..)
. There is no need to load 10.000 numbers into memory. \$\endgroup\$