我正在尝试实现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()是一个用整数位数之和替换整数的函数
您的代码不能针对
52297209396
工作-假设:但是Wikipedia version-per Simon's comment:
^{pr2}$但是,使用上面定义的
digitsum(n)
,我无法重现您的错误:所以我假设
52297209396
是无效的。在数字},
79927398713
(一个工作数字的例子,通过Wikipedia)确实违反了算法的Wikipedia语句(check_luhn()
返回{luhn_check()
返回False
),因此您可以尝试使用它。在相关问题 更多 >
编程相关推荐