I am making a code for validation of credit card but facing some error

78 Views Asked by At
credit = "1234 2347 1845 9023"
credit_card = credit.replace('-','').replace(' ','')
a = len(credit_card)
sum_1 = 0
sum_2 = 0
sum = 0

list_even = []
for i in range (a,0,-1):
    if i%2 != 0:
        sum = sum + int(credit_card[i])
    else:
        list_even.append(int(credit_card[i-1]))


list_even_double = list(map(lambda x: x*2,list_even))

for j in range(len(list_even)):
    if list_even_double[j]>=10:
        sum_2 = sum_2 + list_even[j][0]+ list_even[j][1]
    else:
        sum_1 = sum_1+list_even_double[j]

total = sum_2+sum_1

if total%10 == 0:
    print("Valid")
else:
    print("Not valid")

I am expecting to take odd digit number from end and take the total of it. After that take remaining even digit number and double each of the even digit number. If after doubling there is any 2digit number(23) I want it to take it as (2+3=5).And sum it with the other. after that add those total odd and even if it gets divisible by 10 then its valid or else its not

1

There are 1 best solutions below

0
SIGHUP On

Your implementation of the Luhn algorithm is more cumbersome than it needs to be. Given a string of digits (of arbitrary length), all you need is this:

from itertools import cycle

LMAP = {
        '0': 0,
        '1': 2,
        '2': 4,
        '3': 6,
        '4': 8,
        '5': 1,
        '6': 3,
        '7': 5,
        '8': 7,
        '9': 9
    }

NMAP = {
        '0': 0,
        '1': 1,
        '2': 2,
        '3': 3,
        '4': 4,
        '5': 5,
        '6': 6,
        '7': 7,
        '8': 8,
        '9': 9
    }

def isvalid(n):
    c = cycle((NMAP, LMAP))
    _sum = 0
    for d in n[::-1]:
        _sum += next(c)[d]
    return _sum % 10 == 0
    
print(isvalid('5234123412341239'))
print(isvalid('5234123512341239'))

Output:

True
False