Implementation of Luhn Formula

后端 未结 8 2027
礼貌的吻别
礼貌的吻别 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:10

    I'd keep it simple and easy to read, something like this:

    def luhn(value):
        digits = list(map(int,str(value))
        oddSum = sum(digits[-1::-2])
        evnSum = sum([sum(divmod(2 * d, 10)) for d in digits[-2::-2]])
        return (oddSum + evnSum) % 10 == 0
    

    But there's tons of ways to do the same thing. Obviously, you'd have to do it differently to see the actual output, this just sums up the total to determine if the value is valid.

    Best!

    0 讨论(0)
  • 2020-12-19 16:12

    There are some errors in your code:

    result = divmod(sum_of_digits, 10)
    

    returns a tuple, you need only modulo, that is use

    result = sum_of_digits % 10
    

    Second, to check for validity, you don't omit last digit (that is checksum), but include it in computations. Use

    reverse_sequence = list(int(d) for d in str(int(number[::-1]))) 
    

    And check for result being zero:

    if not result:
        print("[VALID] %s" % number)
    

    Or if you insist on keeping this not needed complexity, check for last digit to be inverse of checksum modulo 10: keep

    reverse_sequence = list(int(d) for d in str(int(number[-2::-1])))
    

    but use

    if (result + last_digit) % 10 == 0:
        print("[VALID] %s" % number)
    

    For a simplier and shorter code, I can give you a reference to my older answer.

    0 讨论(0)
  • 2020-12-19 16:20
    check_numbers = ['49927398716', '4847352989263095', '79927398713', '5543352315777720']
    
    def Luhn_Check(number):
        """
            this function checks a number by using the Luhn algorithm.
    
            Notes (aka - How to Luhn) :
                Luhn algorithm works in a 1 2 1 2 ... order.
                Therefore, in computer speak, 1 0 1 0 ... order
    
                step 1:
                    -> reverse the # so we are not working from right to left (unless you want too)
                    -> double every second number
    
                step 2:
                    -> if the doubled number is greater then 9, add the individual digits of the number to get a single digit number
                        (eg. 12, 1 + 2 = 3)
    
                step 3:
                   -> sum all the digits, if the total modulo is equal to 0 (or ends in zero) then the number is valid...
        """
    
        reverse_numbers = [int(x) for x in number[::-1]] # convert args to int, reverse the numbers, put into a list
        dbl_digits = list() # create empty list
        digits = list(enumerate(reverse_numbers, start=1)) # enumerate numbers starting with an index of 1
    
        for index, digit in digits:
            if index % 2 == 0:  # double every second (other) digit.
    
                doub_digit = digit * 2
                dbl_digits.append(doub_digit - 9) if doub_digit > 9 else dbl_digits.append(doub_digit)
    
            else:
                # if not '0' append to list (this would be the 1 in Luhn algo sequence (1 2 1 2 ...)
                dbl_digits.append(digit)
    
        return sum(dbl_digits) % 10
    
    
    if (__name__ == "__main__"):
        print("Valid Numbers: %s " % [x for x in check_numbers if Luhn_Check(x) == 0])
    
    0 讨论(0)
  • 2020-12-19 16:21

    This is the most concise python formula for the Luhn test I have found:

    def luhn(n):
        r = [int(ch) for ch in str(n)][::-1]
        return (sum(r[0::2]) + sum(sum(divmod(d*2,10)) for d in r[1::2])) % 10 == 0
    

    The above function and other Luhn implementations (in different programming languages) are available in https://www.rosettacode.org/wiki/Luhn_test_of_credit_card_numbers .

    0 讨论(0)
  • 2020-12-19 16:23

    see this Python recipe

    def cardLuhnChecksumIsValid(card_number):
        """ checks to make sure that the card passes a luhn mod-10 checksum """
    
        sum = 0
        num_digits = len(card_number)
        oddeven = num_digits & 1
    
        for count in range(0, num_digits):
            digit = int(card_number[count])
    
            if not (( count & 1 ) ^ oddeven ):
                digit = digit * 2
            if digit > 9:
                digit = digit - 9
    
            sum = sum + digit
    
        return ( (sum % 10) == 0 )
    
    0 讨论(0)
  • 2020-12-19 16:28

    The following might help some people to start with the Luhn algorithm in python.

    num = list(input("Please enter the number to test (no space, no symbols, only \
    numbers): "))
    
    num = list(map(int, num))[::-1] #let's transform string into int and reverse it
    
    for index in range(1,len(num),2):
        if num[index]<5:
            num[index] = num[index] *2
        else: #doubling number>=5 will give a 2 digit number
            num[index] = ((num[index]*2)//10) + ((num[index]*2)%10)
    
    checksum=sum(num)
    
    print("checksum= {}".format(checksum))
    
    if checksum%10 !=0:
        print('the number is not valid')
    else:
        print('the number is valid!')
    
    0 讨论(0)
提交回复
热议问题