Implement the Luhn Algorithm - Implement the Luhn Algorithm

Tell us what’s happening:

I don’t understand why this code doesn’t pass on the test 6.
Where should I fix in this code? How can I pass this case?

Your code so far

def verify_card_number(card_number: str):
    numbers = [int(digit) for digit in card_number if digit.isdecimal()]
    
    for index in range(len(numbers) - 2, -2, -2):
        doubled = numbers[index] * 2
        if doubled > 9:
            doubled_str = str(doubled)
            digit_sum = int(doubled_str[0]) + int(doubled_str[1])
            numbers[index] = digit_sum
        else:
            numbers[index] = doubled

    if sum(numbers) % 10 == 0:
        return "VALID!"
    else:
        return "INVALID!"

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.5 Safari/605.1.15

Challenge Information:

Implement the Luhn Algorithm - Implement the Luhn Algorithm

GitHub Link: freeCodeCamp/curriculum/challenges/english/blocks/lab-luhn-algorithm/68507cadbf36aa089a84ce2d.md at main · freeCodeCamp/freeCodeCamp · GitHub

There is an issue with this indexing:
This loop only doubles digits at fixed positions. The positions of the digits to double depend on whether the total number of digits is odd or even.

Also, instead of:

you can simplify the logic by subtracting 9 whenever the doubled value is greater than 9:

if doubled > 9:
    doubled -= 9

This produces the same result and is the standard approach used in the Luhn algorithm.

Thanks!! I didn’t realize range() could go down to -1. I fixed the stop value to -1, so now the loop always reaches index 0 if the length is even or index 1 if the length is odd, no matter the total number of digits.

And, thank you for the tip about subtracting 9. I understand why that works. This was really helpful.