Luhn Algorithm

Back to General discussions forum

larmstrong     2021-08-14 01:49:12

Hello, I'm having trouble with the Luhn Algorithm problem. For some reason my algorithm works all for two test cases. In fact in one such case my code even adds an extra number. Can someone anaylyis my code and lead me in the right direction

def luhn(digits):
    tot = 0
    for i in range(len(digits)):
        if (i+1) % 2 == 0:
            curr = (int(digits[i]) * 2)
            if curr >= 10:
                curr -= 9
            tot += curr
        else:
            tot += int(digits[i])
    return tot


for _ in range(N):

    digits = list(reversed(list(input())))
    try:
        idx = digits.index('?')
        digits[idx] = 1
        result = luhn(digits)
        for i in range(2, 11):
            if result % 10 == 0:
                break
            digits[idx] = i
            result = luhn(digits)
    except ValueError:
        result = luhn(digits)
        i = len(digits)-2
        while i >= 1:
            if result % 10 == 0:
                break
            digits[i-1], digits[i] = digits[i], digits[i-1]
            result = luhn(digits)
            if result % 10 == 0:
                break
            else:
                digits[i-1], digits[i] = digits[i], digits[i-1]
            i -= 1
qwerty     2021-08-14 05:35:22

Well, there are definitely some errors:

for i in range(2, 11):

I think it should be

for i in range(2, 10):

...because 10 is not a digit.

i = len(digits)-2

Why you are not processing first digit (last of reversed array)?

i = len(digits)-1

... is better index to start with.

Please login and solve 5 problems to be able to post at forum