Here is a simple piece of code in Python. It 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 N
).
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[0]) * 1,int(p[1]) * 3,int(p[2]) * 7,int(p[3]) * 9,int(p[4]) * 1,int(p[5]) * 3,int(p[6]) * 7,int(p[7]) * 9,int(p[8]) * 1,int(p[9]) * 3,int(p[10]) * 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: time: 0.03s
, memory: 4.1M
, where the best solutions (submitted in Python 2.7) got: time: 0.01s
and memory: 3.7M
.
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.