Lung's algorythm question
i checked the solution and there are a couple of questions came up:
1: why reverse the list
2 if the multiplied result is 2 digits it deduces 9. why is that so?
following the stated rules, my code work according to the lecture but fail with a real card.
the given solution works fine with a real card.
it seems that the explained rules are different than the ones used in the solution or i missed something.
thanks,
peter
def Luhn(n, N):
"""
n: card number in text
N: card number lenght
return valid or not
"""
n = n.replace(' ', '')
if len(n) != N:
return 'not valid'
# rule 1
even = [int(v)*2 for i, v in enumerate(n) if i%2 != 0]
sum1 = sum([int(i) for i in ''.join([str(i) for i in even])]) #separate the digits by converting them str and back to int
#rule 2
sum2 = sum1 + sum([int(v) for i, v in enumerate(n) if i%2 == 0])
#print(even, sum1,sum2)
#rule 3
if sum2%10 == 0:
return 'valid'
else:
return 'invalid'
Hey Peter,
Thank you for your question and the great algorithm you have implemented!
The discrepancy between your algorithm and Giles' one comes from the fact that they work differently if the number of digits on the credit card is even.
Consider the following number (which is one of the numbers Giles provides in the Jupyter notebook):
5 6 1 0 5 9 1 0 8 1 0 1 8 2 5 0
Following the algorithm Giles explains in the video, we will need to multiply by 2 the following digits (marked in bold):
5 6 1 0 5 9 1 0 8 1 0 1 8 2 5 0
Following your algorithm, however, provided I have called the function in the following way
Luhn(number, 16)
,
the bolded digits below will be multiplied instead:
5 6 1 0 5 9 1 0 8 1 0 1 8 2 5 0
Usually, credit cards contain 16 digits, so maybe that is why entering a real credit card number didn't work out :)
What I would suggest is adapt your code such that it works for both even- and odd-numbered cards.
Hope this also answers the first two questions you had!
Best wishes,
365 Hristina
ah, i got it all...
the video actually says it is the second from the BACK. thats the part i missed. thats why the code reverse the list. ok.
deducing from numbers between 10 and 19 gives back the sum of the digits:
12 -9 = 1+2
17 -9 = 1 +7
so these two makes the same list but first by the video, second with math trick
sum1 = [int(ii) for ii in ''.join([str(i) for i in even])]
sum1 = [i if i < 10 else i - 9 for i in even]
it works any lenght of card numbers provided it follows the rules.
thank you!