def luhn(card, toCodePoint = None, toIter = None, base = 10): toCodePoint = toCodePoint if toCodePoint is not None else lambda x: int(x, base) try: offset = 1 + len(card) % 2 cn = enumerate((toCodePoint(x) for x in card), offset) return sum(sum(divmod(n * (1 + c % 2), base)) for c, n in cn) % base except TypeError: toIter = toIter if toIter is not None else lambda x: str(x) luhn(toIter(card), toCodePoint, toIter, base) def luhnValid(card, toCodePoint = None, toIter = None, base = 10): return luhn(card) == 0 def luhnCheckDigit(card, toCodePoint = None, toIter = None, base = 10): return (10 - luhn(card)) % 10 luhntestnumbers = ( '378282246310005', # amex1 '371449635398431', # amex2 '378734493671000', # amex corporate '6011111111111117', # discover1 '6011000990139424', # discover2 '5555555555554444', # mc1 '5105105105105100', # mc2 '4111111111111111', # visa1 '4012888888881881', # visa2 '4222222222222', # visa3 ) if __name__ == '__main__': for x in luhntestnumbers: #assert isvalid(x) == True print luhnValid(x), x
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question