dimanche 29 juillet 2018

Python: Luhn's algorithm / if statement never executes

I am trying to implement the Luhn's algorithm to check for credit card number validity. To do this every second digit needs to be multiplied by 2 and if the result is >9 it then is replaced by the sum of the digits.

def luhn_check(creditcardnr):
"""
check if credit card number is valid using the Luhn's algorithm
"""

som = 0
for i, digit in enumerate([int(x) for x in str(creditcardnr)]):
    if i in range(1, len(str(creditcardnr))-1,2):
        digit *= 2
        if digit > 9:
            digit -= digitsum(digit)
    som += digit
    print('digit :',digit,'    sum :',som)

return som % 10 == 0

When I run this code I get as result

digit : 5    sum : 5
digit : 2    sum : 7
digit : 2    sum : 9
digit : 9    sum : 18
digit : 7    sum : 25
digit : 2    sum : 27
digit : 0    sum : 27
digit : 9    sum : 36
digit : 3    sum : 39
digit : 9    sum : 48
digit : 6    sum : 54
False

the second sum should be 9 not 7

Aucun commentaire:

Enregistrer un commentaire