Implementation of Luhn Formula

后端 未结 8 2122
礼貌的吻别
礼貌的吻别 2020-12-19 15:38

I was trying to implement the Luhn Formula in Python. Here is my code:

import sys


def luhn_check(number):
    if number.isdigit():
        last_digit = int(         


        
8条回答
  •  执笔经年
    2020-12-19 16:33

    I think the algorithm is not correct.

    The second step you need to sum the digits of the products instead of substract 9. Reference: Wikipedia.

    In the Wikipedia you have this example:

    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
    
    
    result = is_luhn_valid(4532015112830366)
    print 'Correct:' + str(result)
    result = is_luhn_valid(6011514433546201)
    print 'Correct:' + str(result)
    result = is_luhn_valid(6771549495586802)
    print 'Correct:' + str(result)
    

    Result:

    >>>Correct:True
    >>>Correct:True
    >>>Correct:True
    

提交回复
热议问题