Implementation of Luhn Formula

后端 未结 8 2145
礼貌的吻别
礼貌的吻别 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!

提交回复
热议问题