使用Luhn算法Python验证信用卡号

问题描述:

我正在尝试在Python中实现Luhn算法.这是我的代码

I am trying to implement Luhn algorithm in Python. Here is my code

def validate(n):
    if len(str(n)) > 16:
        return False
    else:
        if len(str(n)) % 2 == 0:
            for i in str(n[0::2]):
                digit = int(str(n[i])) * 2
                while digit > 9:
                    digit = sum(map(int, str(digit)))
            dig_sum = sum(map(int, str(n)))
            return True if dig_sum % 10 == 0 else False
        elif len(str(n)) % 2 != 0:
            for i in str(n[1::2]):
                digit = int(str(n[i])) * 2
                while digit > 9:
                    digit = sum(map(int, str(digit)))
            dig_sum = sum(map(int, str(n)))
            return True if dig_sum % 10 == 0 else False

我不断收到错误消息

TypeError: 'int' object has no attribute '__getitem__

以下是Lunh Algorith的python实现,用于检测有效的信用卡号.函数以数字作为字符串,并返回其有效信用卡号与否.

Following is python implementation of Lunh Algorith to detect a valid credit card number. Function takes a number as string and return whether its valid credit card or not.

它基于以下链接中提到的步骤:

Its based on the steps mentioned in the following link: https://www.codeproject.com/Tips/515367/Validate-credit-card-number-with-Mod-algorithm

第1步-从校验位开始,将其他两位的值加倍(每2位从右到左)

Step 1 - Starting with the check digit double the value of every other digit (right to left every 2nd digit)  

第2步-如果将数字加倍后得到两位数字,则将这些数字加起来得到一位数字.这将导致八个单位数字.

Step 2 - If doubling of a number results in a two digits number, add up the digits to get a single digit number. This will results in eight single digit numbers.

第3步-现在将未加倍的数字添加到奇数位

Step 3 - Now add the un-doubled digits to the odd places

第4步-将该数字中的所有数字相加

Step 4 - Add up all the digits in this number

如果最终金额可以被10整除,则信用卡号有效.如果不能被10整除,则该数字无效.

If the final sum is divisible by 10, then the credit card number is valid. If it is not divisible by 10, the number is invalid. 

def luhn(ccn):
    c = [int(x) for x in ccn[::-2]] 
    u2 = [(2*int(y))//10+(2*int(y))%10 for y in ccn[-2::-2]]
    return sum(c+u2)%10 == 0

#Test
print(luhn("49927398716"))