Skip to content

Instantly share code, notes, and snippets.

@matuu
Created November 27, 2013 11:14
Show Gist options
  • Select an option

  • Save matuu/7674078 to your computer and use it in GitHub Desktop.

Select an option

Save matuu/7674078 to your computer and use it in GitHub Desktop.
Luhn checksum
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 calculate_luhn(partial_card_number):
check_digit = luhn_checksum(int(partial_card_number) * 10)
return check_digit if check_digit == 0 else 10 - check_digit
def is_luhn_valid(card_number):
return luhn_checksum(card_number) == 0
@matuu
Copy link
Copy Markdown
Author

matuu commented Nov 27, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment