lilsnyderio
lilsnyderio

Reputation: 53

Validate Credit Card Number Using Luhn Algorithm Python

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

I keep getting the error

TypeError: 'int' object has no attribute '__getitem__

Upvotes: 2

Views: 3709

Answers (2)

K246
K246

Reputation: 1107

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

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

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.

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

Step 4 - Add up all the digits in this number

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"))

Upvotes: 3

amit
amit

Reputation: 178441

It is hard to tell without the complete error message, but it is likely because you confused in some places where you put the indexing and where you put the string conversion, for example: for i in str(**n[1::2]**) and digit = int(str(**n[i]**)) * 2

A good way to handle it is to just create a temporary variable n_str = str(n), and use it instead of str(n) over and over again.

Upvotes: 1

Related Questions