Implementation of Luhn Formula

2020-02-12 13:21发布

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(str(number)[-1])
        reverse_sequence = list(int(d) for d in str(int(number[-2::-1])))

        for i in range(0, len(reverse_sequence), 2):
            reverse_sequence[i] *= 2

        for i in range(len(reverse_sequence)):
            if reverse_sequence[i] > 9:
                reverse_sequence[i] -= 9

        sum_of_digits = 0
        for i in range(len(reverse_sequence)):
            sum_of_digits += reverse_sequence[i]

        result = divmod(sum_of_digits, 10)

        if result == last_digit:
            print("[VALID] %s" % number)
        else:
            print("[INVALID] %s" % number)
        quit()

    print("[ERROR] \" %s \" is not a valid sequence." % number)
    quit()


def main():
    if len(sys.argv) < 2:
        print("Usage: python TLF.py <sequence>")
        quit()

    luhn_check(sys.argv[1])

if __name__ == '__main__':
    main()

But it isn't working properly:

[INVALID] 4532015112830366
[INVALID] 6011514433546201
[INVALID] 6771549495586802

and so on...

But the logic of the code seems OK to me. I followed this workflow:

The Luhn Formula:

  1. Drop the last digit from the number. The last digit is what we want to check against Reverse the numbers

  2. Multiply the digits in odd positions (1, 3, 5, etc.) by 2 and subtract 9 to all any result higher than 9

  3. Add all the numbers together

  4. The check digit (the last number of the card) is the amount that you would need to add to get a multiple of 10 (Modulo 10)

7条回答
欢心
2楼-- · 2020-02-12 14:20

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

def luhn(value):
    digits = 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!

查看更多
登录 后发表回答