python – 信用卡号验证器无法正常工作
作者:互联网
def checksum(card_without_check):
card_without_check = card_without_check[-1::-1]
def numbers(string):
return [int(x) for x in string]
print(card_without_check)
odd_numbers = numbers(card_without_check[0::2])
even_numbers = numbers(card_without_check[1::2])
odd_numbers = [x * 2 for x in odd_numbers]
odd_numbers = [x - 9 if x > 9 else x for x in odd_numbers]
print(even_numbers)
print(odd_numbers)
return sum(odd_numbers) + sum(even_numbers)
def check(checksum, check):
return checksum % 10 == int(check)
card_number = input("Enter card number:\n")
print(checksum(card_number[:-1]))
print("Card is", check(checksum(card_number[:-1]), card_number[-1]))
此算法似乎适用于“4556737586899855”等示例,但不适用于“30569309025904”等示例.我已经按照这个过程进行了操作,并且无法找到处理数字的缺陷,我可能只是错过了这里的一些难题.
解决方法:
我使用这个解决方案来解决基于Luhn公式的代码问题:
def checksum(n):
nums = reversed(list(map(int, n)))
doubled = (ele * 2 if ind % 2 else ele for ind, ele in enumerate(nums))
return not sum(sum(map(int, str(ele))) for ele in doubled) % 10
步骤列在问题描述中:
From the rightmost digit, which is the check digit, moving left, double the value of every second digit; if the product of this doubling operation is greater than 9 (for example, 7×2=14), then sum the digits of the products (for example, 12:1+2=3, 14:1+4=5).
Take the sum of all the digits.
If the total modulo 10 is equal to 0 (if the total ends in zero) then, according to the Luhn formula, the number is valid; otherwise, it is not valid.
标签:python,checksum,luhn 来源: https://codeday.me/bug/20191008/1875398.html