pythonluhn

How to solve Luhn algoritm


there is a lot of information about how to write Luhn algortim. I'm trying it too and I think that I'am very close to succes but I have some mistake in my code and dont know where. The test card is VALID card but my algorithm says otherwise. Don't you know why? Thx for help

test = "5573497266530355"
kazde_druhe = []
ostatni = []

for i in test:
    if int(i) % 2 == 0:
        double_digit = int(i) * 2

        if double_digit > 9:
            p = double_digit - 9
            kazde_druhe.append(p)
        else:
            kazde_druhe.append(double_digit)
    else:
        ostatni.append(int(i))

o = sum(ostatni)
k = sum(kazde_druhe)

total = o+k

if total % 10 == 0:
    print(f"Your card is valid ")
else:
    print(f"Your card is invalid ")

Finally! Thank you all for your help. Now it is working :-)

        test = "5573497266530355" kazde_druhe = [] ostatni = []
        
        for index, digit in enumerate(test):
            if index % 2 == 0:
                double_digit = int(digit) * 2
                print(double_digit)
        
                if double_digit > 9:
                    double_digit = double_digit - 9
                    kazde_druhe.append(double_digit)
                else:
                    kazde_druhe.append(double_digit)
            else:
                ostatni.append(int(digit))
    
     o = sum(ostatni)
    
     k = sum(kazde_druhe) 
    
    total = o+k if total % 10 == 0:
            print(f"Your card is valid ")
 else:
            print(f"Your card is invalid ")

Solution

  • This code works. :)

    I fixed you code as much as i could.

    test = "5573497266530355"
    #test = "3379513561108795"
    
    nums = []
    
    for i in range(len(test)):
        if (i % 2) == 0:
            num = int(test[i]) * 2
            
            if num > 9:
                num -= 9
    
            nums.append(num)
        else:
            nums.append(int(test[i]))
    
    print(nums)
    print((sum(nums) % 10) == 0)
    

    I found where your code went wrong.

    On the line:

    for i in test:
        if int(i) % 2 == 0:
    

    It should be:

    for i in range(len(test)):
        if i % 2 == 0:
    

    You should not be using the element of the string you should be using the index of the element.