Luhn Algorithm need help

Back to Problem Solutions forum

dlardashev     2017-01-21 10:17:28

Please help me. I solved this tast (as I thinked) but in my answer always few mistakes, despite test-example solved correct and most another too. This my code:

def get_sum_four(n):

    n1 = int(n[0])
    n2 = int(n[1]) * 2
    if n2 > 9:
        n2 = n2 - 9

    n3 = int(n[2])
    n4 = int(n[3]) * 2
    if n4 > 9:
        n4 = n4 - 9

    return (n1 + n2 + n3 + n4)

def check_sum(D):
    return get_sum_four(D[:4]) + get_sum_four(D[4:8]) + get_sum_four(D[8:12]) + get_sum_four(D[12:])


def find_lost_number(N):
    N = N[::-1]
    N = list(N)

    index = N.index('?')
    N.remove('?')

    for i in range(10):
        N.insert(index, str(i))

        if check_sum(N) % 10 == 0:
            return N

        N.pop(index)



times = int(input())

for i in range(times):
    wrong_number = input()

    if '?' in wrong_number:
        correct_number = find_lost_number(wrong_number)
        print (''.join(correct_number)[::-1], end = ' ')
    else:
        wrong_list = list(wrong_number)
        count = 0
        while count < len(wrong_list) - 2:
            wrong_list[count], wrong_list[count - 1] = wrong_list[count - 1], wrong_list[count]

            if check_sum(wrong_list[::-1]) % 10 == 0:
                print (''.join(wrong_list),end = ' ')
                break

            wrong_list[count], wrong_list[count - 1] = wrong_list[count - 1], wrong_list[count]
            count += 1

Where is mistake which I not see?..

P. S. Sorry for my English.

Quandray     2017-01-21 13:34:31
User avatar

Try this input

1
3379366672770418

If you still need help, please provide an example of a card number that your code gets wrong.

dlardashev     2017-01-21 13:59:05

Thanks, man. I made very stupid mistake :) Sometimes it need simple rest and try again :)

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