Implementation of Luhn Formula

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

提交回复
热议问题