Skip to main content
 首页 » 编程设计

python之信用卡号码验证器无法正常工作

2025年05月04日9xing901022

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”等示例。我遵循了这个过程,但没有发现它处理数字的方式存在缺陷,我可能只是在这里遗漏了一些拼图。

我正在遵循大纲 here并使用示例 here .

请您参考如下方法:

我将此解决方案用于基于 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.