Instantly share code, notes, and snippets.

Embed
What would you like to do?
Luhn validation algorithm for credit cards.
"""
Python implementation of the Luhn algorithm.
Refer to: http://en.wikipedia.org/wiki/Luhn_algorithm
>>> is_luhn_valid(79927398713)
True
>>> is_luhn_valid(79927398714)
False
>>> is_luhn_valid(4532990475689429)
True
>>> is_luhn_valid(4532990475689420)
False
>>> is_luhn_valid(4556278174544876)
True
>>> is_luhn_valid(4556278174544871)
False
>>> is_luhn_valid(5325806143405717)
True
>>> is_luhn_valid(5325806143405712)
False
>>> is_luhn_valid(5459209022644894)
True
>>> is_luhn_valid(5459209022644895)
False
>>> calculate_luhn(7992739871)
3
>>> calculate_luhn(453299047568942)
9
>>> calculate_luhn(455627817454487)
6
>>> calculate_luhn(532580614340571)
7
>>> calculate_luhn(545920902264489)
4
"""
def luhn_checksum(card_number):
def digits_of(n):
return [int(d) for d in str(n)]
digits = digits_of(card_number)
odd_digits = digits[-1::-2]
even_digits = digits[-2::-2]
checksum = 0
checksum += sum(odd_digits)
for d in even_digits:
checksum += sum(digits_of(d*2))
return checksum % 10
def is_luhn_valid(card_number):
return luhn_checksum(card_number) == 0
def calculate_luhn(partial_card_number):
return 10 - luhn_checksum(int(partial_card_number) * 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment