Skip to content

Instantly share code, notes, and snippets.

@nickylimjj
Last active June 15, 2017 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickylimjj/ca535c56222472b453343c166b143495 to your computer and use it in GitHub Desktop.
Save nickylimjj/ca535c56222472b453343c166b143495 to your computer and use it in GitHub Desktop.
nric-cert.py
# nric-cert.py
# verifies a Singaporean NRIC
# motivated by video from The Fun Social - How did your NRIC
# number come about?
# date created: June 15, 2017
# author: Nicky Lim
import sys
assert len(sys.argv) == 2, "Usage: python nric-cert.py <NRIC>"
nric = sys.argv[1].lower()
prefix = nric[0]
digits = [int(c) for c in nric[1:-1]] # represented as list of ints
suffix = nric[-1]
assert len(prefix) == 1 \
and len(digits) == 7 \
and len(suffix) == 1, "invalid length"
assert prefix in ['s','t','f','g'], "invalid prefix"
# for 's'-prefix holders, matches age from 1968 and above, else starts with
# 0 or 1
if (prefix == 's'):
age = digits[0]*10 + digits[1]
fd = int(digits[0]) # first digit
assert (68 <= age and age <= 99) \
or fd == 0 or fd == 1, "invalid age"
# verify digits
weights = [2,7,6,5,4,3,2]
total = sum([a*b for a,b in zip(digits,weights)])
if (prefix in ['t','g']):
total += 4
calc_suffix = ['x','w','u','t','r','q','p','n','m','l','k']\
[total%11]
# s or t prefix
else:
calc_suffix = ['j','z','i','h','g','f','e','d','c','b','a']\
[total%11]
assert (calc_suffix == suffix), "invalid suffix or wrong digits. calculations \
yield the suffix to be {}.".format(calc_suffix.upper())
print("NRIC: {0} is valid!".format(nric))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment