Created
February 18, 2012 18:14
-
-
Save danpalmer/1860498 to your computer and use it in GitHub Desktop.
Python Luhn Implementation, Draft 2
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
import sys | |
def process_input(input_str): | |
input_str = input_str[::-1] | |
states = [] | |
index = 0 | |
mask = [] | |
toggle = {1:2, 2:1} | |
m1 = 1 | |
# for each character, add it up | |
for c in input_str: | |
if not c.isdigit(): | |
continue | |
num = int(c) | |
m2 = m1 | |
m1 = toggle[m1] | |
for i in range(len(states)): | |
temp = num * m2 | |
for c2 in str(temp): | |
states[i][0] += int(c2) | |
states[i][1] += [index] | |
m2 = toggle[m2] | |
states.append([num, [index]]) | |
index += 1 | |
# check which indices work out | |
check = len(states) - 14 | |
for i in range(check + 1): | |
validate(states[i], mask) | |
if len(states) >= 16: states.pop(0) | |
# for every index that needs masking, mask it | |
l = list(input_str) | |
for i in mask: | |
l[i+1] = 'X' | |
input_str = ''.join(l) | |
return ''.join(input_str[::-1]) | |
#return input_str | |
def validate(index, mask): | |
if type(index[0]) == int: | |
if ((index[0] % 10) == 0): | |
mask += index[1] | |
if __name__ == "__main__": | |
result = process_input(sys.stdin.readline()) | |
sys.stdout.write(result) | |
sys.stdout.flush() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment