Back to General discussions forum
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
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.