Created
May 8, 2017 21:11
-
-
Save TApicella/4c11c4a3f2ff0c0c6af91462456b71b4 to your computer and use it in GitHub Desktop.
RosettaCode_validateISIN created by tapicella - https://repl.it/HnEm/27
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
''' | |
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. | |
Replace letters with digits, by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 →1030000033311635103. | |
Perform the Luhn test on this base-10 number. | |
US0378331005:TRUE | |
US0373831005:FALSE | |
U50378331005:FALSE | |
AU0000XVGZA3:TRUE | |
AU0000VXGZA3:TRUE | |
FR0000988040:TRUE | |
US03378331005: FALSE | |
Luhn test: | |
Reverse the order of the digits in the number. | |
Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1 | |
Taking the second, fourth ... and every other even digit in the reversed digits: | |
Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits | |
Sum the partial sums of the even digits to form s2 | |
If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test. | |
49927398716 TRUE | |
49927398717 FALSE | |
1234567812345678 FALSE | |
1234567812345670 TRUE | |
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers | |
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number | |
''' | |
import functools, string | |
def ps(n): | |
return (n//10)+(n%10) | |
def LuhnTest(n): | |
s_n = str(n)[::-1] | |
odds = s_n[0::2] | |
evens = s_n[1::2] | |
s1 = 0 | |
s2 = 0 | |
for o in odds: | |
s1 += int(o) | |
for e in evens: | |
s2 += ps(2*int(e)) | |
return((s1+s2)%10 == 0) | |
def validate(n): | |
if len(n) != 12: | |
return False | |
alpha = list(string.ascii_uppercase) | |
if n[0] not in alpha or n[1] not in alpha or n[11] in alpha: | |
return False | |
base10 = "" | |
for c in n: | |
if c in alpha: | |
base10 += str(10+alpha.index(c)) | |
else: | |
base10 += c | |
return LuhnTest(base10) | |
print(validate("US0378331005")) | |
print(validate("US0373831005")) | |
print(validate("U50378331005")) | |
print(validate("AU0000XVGZA3")) | |
print(validate("AU0000VXGZA3")) | |
print(validate("FR0000988040")) | |
print(validate("FR000098804O")) | |
print(validate("US03378331005")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment