Last active
May 25, 2017 19:07
-
-
Save sr105/babea6cc32d83af20dbbd55db177eb6d to your computer and use it in GitHub Desktop.
Luhn algorithm
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
def luhn(cc, debug=False): | |
double = True | |
sum = 0 | |
doubled = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9] | |
if debug: | |
print('{:15}{:15}{:15}{}'.format('digit', 'sum digit', 'sum', 'double')) | |
for n in (int(c) for c in reversed(cc.replace(' ', ''))): | |
value = doubled[n] if double else n | |
if debug: | |
print('{:<15}{:<15}{:<15}{}'.format(n, value, sum, double)) | |
sum += doubled[n] if double else n | |
double = not double | |
return (9 * sum) % 10 | |
def luhn2(cc): | |
doubled = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9] | |
nums = (int(c) for c in reversed(cc.replace(' ', ''))) | |
total = sum((doubled[n], n)[i % 2] for i, n in enumerate(nums)) | |
return (9 * total) % 10 | |
def luhn3(cc): | |
doubled = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9] | |
nums = [int(c) for c in cc.replace(' ', '')] | |
total = sum((doubled[n] for n in nums[-1::-2]), sum(nums[-2::-2])) | |
return (9 * total) % 10 | |
def luhn4(cc): | |
sums = ((0, 2, 4, 6, 8, 1, 3, 5, 7, 9), | |
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)) | |
nums = (int(c) for c in reversed(cc.replace(' ', ''))) | |
total = sum(sums[i % 2][n] for i, n in enumerate(nums)) | |
return (9 * total) % 10 | |
luhn('4038 1287 8520 ') | |
luhn('4038 1287 8520 ', debug=True) | |
luhn2('4038 1287 8520 ') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment