def checksum(card_without_check):
card_without_check = card_without_check[-1::-1]
def numbers(string):
return [int(x) for x in string]
print(card_without_check)
odd_numbers = numbers(card_without_check[0::2])
even_numbers = numbers(card_without_check[1::2])
odd_numbers = [x * 2 for x in odd_numbers]
odd_numbers = [x - 9 if x > 9 else x for x in odd_numbers]
print(even_numbers)
print(odd_numbers)
return sum(odd_numbers) + sum(even_numbers)
def check(checksum, check):
return checksum % 10 == int(check)
card_number = input("Enter card number:\n")
print(checksum(card_number[:-1]))
print("Card is", check(checksum(card_number[:-1]), card_number[-1]))
This algorithm appears to work on examples like "4556737586899855", but not on examples like "30569309025904". I've followed the process and can't find flaws in how it's handling the numbers, I'm probably just missing some piece of the puzzle here.
You nearly got it right, except for the initial cutting off of the last digit. You cannot reverse and slice one off in one slice notation but in two:
And then in the call to the checksum() routine the logic went overboard. Try this:
An input of 4556737586899855 yields:
Valid? 589986857376554 [1, 9, 7, 7, 5, 5, 1, 8] [8, 9, 6, 5, 3, 6, 5] True
I used this solution for a codeeval problem based on Luhn's formula:
The steps are listed in the problem description:
This is the code for MOD10 (the Luhn algorithm) that I wrote from the description on (the Norwegian) Wikipedia:
Looks like you might have skipped the special handling when the
entallsiffer
is zero, and you're also not subtracting from 10, meaning you'll only get the correct answer when the control/checksum digit is5
.Here is a credit card utils library I wrote that covers luhn checksum as well as other credit card checks.
Please feel free to comment if there is anything missing that is useful. Cheers.