Luhn algorithm in Python
October 09, 2009 03:39:22 Last update: October 09, 2009 19:25:50
Luhn algorithm in Python just for the heck of it.
def doLuhn(s, evenPos): s = str(s) sum = 0 for d in reversed(s): d = int(d) assert 0 <= d <= 9 if evenPos: d *= 2 if d > 9: d = (d % 10) + 1 sum += d evenPos = not evenPos return sum def luhnValidation(n): return doLuhn(n, False) % 10 == 0 def generateCheckDigit(n): return 10 - (doLuhn(n, True) % 10) if __name__ == '__main__': import sys if len(sys.argv) < 2: print "%s <number> [g]" % sys.argv[0] sys.exit(1) elif len(sys.argv) == 2: n = sys.argv[1] if luhnValidation(n): print "%s is valid" % n else: print "%s is not valid" % n else: n = sys.argv[1] print "%s%s" % (n, generateCheckDigit(n))
Easy email testing with http://www.ximailstop.com