Implementation of Luhn Formula

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

提交回复
热议问题