Python:Luhn的算法/if语句从不执行

2024-09-28 01:30:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试实现Luhn算法来检查信用卡号码的有效性。为此,每第二个数字需要乘以2,如果结果是>;9,则用位数和替换。在

def luhn_check(creditcardnr):
"""
check if credit card number is valid using the Luhn's algorithm
"""

som = 0
for i, digit in enumerate([int(x) for x in str(creditcardnr)]):
    if i in range(1, len(str(creditcardnr))-1,2):
        digit *= 2
        if digit > 9:
            digit -= digitsum(digit)
    som += digit
    print('digit :',digit,'    sum :',som)

return som % 10 == 0

当我运行这个代码时,我得到的结果是

^{2}$

第二个总数应该是9而不是7

digitsum()是一个用整数位数之和替换整数的函数


Tags: in算法forifcheck整数信用卡号码
1条回答
网友
1楼 · 发布于 2024-09-28 01:30:41

您的代码不能针对52297209396工作-假设:

def digitsum(n):
    s = 0
    while n:
        s += n % 10
        n //= 10
    return s

但是Wikipedia version-per Simon's comment

^{pr2}$

但是,使用上面定义的digitsum(n),我无法重现您的错误:

the second sum should be 9 not 7

('digit :', 5, '    sum :', 5)
('digit :', 4, '    sum :', 9)
('digit :', 2, '    sum :', 11)
('digit :', 9, '    sum :', 20)
('digit :', 7, '    sum :', 27)
('digit :', 4, '    sum :', 31)

所以我假设52297209396是无效的。在

数字79927398713(一个工作数字的例子,通过Wikipedia)确实违反了算法的Wikipedia语句(check_luhn()返回{},luhn_check()返回False),因此您可以尝试使用它。在

相关问题 更多 >

    热门问题