Last active
January 3, 2016 19:09
-
-
Save rctay/8506594 to your computer and use it in GitHub Desktop.
Computing/verifying licence plates http://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Singapore#Checksum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'''A-1''' | |
alpha2num = lambda s: (ord(char) - ord('A') + 1 for char in s) | |
'''0-0''' | |
num2num = lambda s: (ord(num) - ord('0') for num in s) | |
import itertools | |
import re | |
LOOKUP = ('A', 'Z', 'Y', 'X', 'U', 'T', 'S', 'R', 'P', 'M', 'L', 'K', 'J', 'H', 'G', 'E', 'D', 'C', 'B') | |
ZIP = (9, 4, 5, 4, 3, 2) | |
BASE = 19 | |
pat = re.compile(r'([A-Z]+)([0-9]+)([A-Z]?)') | |
def run(plate): | |
m = re.match(pat, plate) | |
if not m: | |
return | |
prefix, body, p_letter = m.groups() | |
it = itertools.chain(alpha2num(prefix[-2:]), num2num(body)) | |
it = zip(ZIP, it) # ZIP first ensures result is bounded by length of 1st arg instead of 2nd | |
x = reduce(lambda s,(a,b): s+a*b, it, 0) # hmm destructuring works in arguments... | |
letter = LOOKUP[x % BASE] | |
# two modes - 1) verify, or 2) compute | |
if p_letter == '': | |
return letter | |
else: | |
return p_letter == letter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment