Here is a solution to the SPOJ's JPESEL problem. Basically the problem was to calculate cross product of 2 vectors modulo 10. If there is a positive remainder, it's not a valid PESEL number; (return
D) if the remainder equals
0, it's a valid number (return
import re, sys n = input() t = [1,3,7,9,1,3,7,9,1,3,1] while(n): p = map(int, re.findall('.',sys.stdin.readline())) # Another approach I've tried in orer to save some memory - didn't help: # print 'D' if sum([int(p) * 1,int(p) * 3,int(p) * 7,int(p) * 9,int(p) * 1,int(p) * 3,int(p) * 7,int(p) * 9,int(p) * 1,int(p) * 3,int(p) * 1]) % 10 == 0 else 'N' print 'D' if ( sum(p*q for p,q in zip(t,p)) % 10 ) == 0 else 'N' n-=1
The solution above got the following results at SPOJ:
where the best solutions (submitted in Python 2.7) got:
How can I optimize this code in terms of time and memory used?
Note that I'm using different function to read the input, as
sys.stdin.readline() is the fastest one when reading strings and
input() when reading integers.