Last active
August 29, 2015 14:16
-
-
Save RobertSudwarts/c94edb12ffc9ea7abf85 to your computer and use it in GitHub Desktop.
python implementation of mod10 check digit for invoices etc
This file contains hidden or 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
# 12345 -> '54321' [the returned value is a string] | |
reverse = lambda x: str(x)[::-1] | |
# translate each element of x to a string and join eg. [18, 3, 2] -> '1832' | |
strjoin = lambda x: "".join(map(str, x)) | |
# '1832' -> 1 + 8 + 3 + 2 -> 14 | |
sumstr = lambda x: sum(int(n) for n in x) | |
# compute the number which must be added to `x` to get to the nearest 10 | |
# eg 18 -> 2 (20-18=2) or 43 -> 7 (50-43=7) | |
mod_ten = lambda x: int((10 - (x % 10)) % 10) | |
def doubler(strnum): | |
'''yield double for every other digit | |
''' | |
for i, n in enumerate(strnum): | |
n = int(n) | |
yield n if i % 2 else n*2 | |
def check_digit(num): | |
'''compute the check digit for a given number | |
>>> check_digit(1234) | |
4 | |
>>> check_digit(1236) | |
9 | |
''' | |
rnum = reverse(num) | |
v = [j for j in doubler(rnum)] | |
value = sumstr(strjoin(v)) | |
return mod_ten(value) | |
def checked_num(num): | |
'''return invoice number formatted with its check-digit | |
>>> checked_num(1502237) | |
'1502237-9' | |
''' | |
return "%d-%d" % (num, check_digit(num)) | |
def check(invoice_number): | |
'''verifiy that a given invoice number (with its check digit) checks out | |
>>> check('1502237-9') | |
True | |
>>> # notice the transposition from the above | |
>>> check('1502273-9') | |
False | |
''' | |
n, c = invoice_number.split('-') | |
return check_digit(int(n)) == int(c) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment