鲁恩公式的实现 [英] Implementation of Luhn Formula

查看:95
本文介绍了鲁恩公式的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Python中实现 Luhn公式,这是我的代码:

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()

但是它不能正常工作:

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

以此类推...

但是代码的逻辑对我来说似乎还可以.我遵循此工作流程:

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

鲁恩公式:

  1. 从数字中删除最后一位数字.最后一位是我们要检查的 反转数字

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

将奇数位置(1、3、5等)的数字乘以2,并对所有高于9的结果减去9

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

将所有数字加在一起

校验位(卡的最后一个数字)是您要获得10的倍数(模10)所需的金额

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)

推荐答案

我认为该算法不正确.

I think the algorithm is not correct.

第二步,您需要对产品的数字求和而不是减去9.参考:维基百科.

The second step you need to sum the digits of the products instead of substract 9. Reference: Wikipedia.

在Wikipedia中,您有以下示例:

In the Wikipedia you have this example:

def luhn_checksum(card_number):
    def digits_of(n):
        return [int(d) for d in str(n)]
    digits = digits_of(card_number)
    odd_digits = digits[-1::-2]
    even_digits = digits[-2::-2]
    checksum = 0
    checksum += sum(odd_digits)
    for d in even_digits:
        checksum += sum(digits_of(d*2))
    return checksum % 10

def is_luhn_valid(card_number):
    return luhn_checksum(card_number) == 0


result = is_luhn_valid(4532015112830366)
print 'Correct:' + str(result)
result = is_luhn_valid(6011514433546201)
print 'Correct:' + str(result)
result = is_luhn_valid(6771549495586802)
print 'Correct:' + str(result)

结果:

>>>Correct:True
>>>Correct:True
>>>Correct:True

这篇关于鲁恩公式的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆