Last answered:

24 Feb 2022

Posted on:

23 Feb 2022

1

Luhn's algorithm Solution

Hi !
First, I would like to thanks  Mr. Giles for making learning so fun and gradually increasing levels on every next topic. Moreover, I love his accent.
However, the solution provided for Luhn algorithm which I'm mentioning below -
******************************************************************
1.num_list = [int(char) for char in number]
2.num_len = len(num_list)
3.num_list_rev = num_list[::-1]
4.double = 0
5.single = 0
6.for i in range(0,num_len):
7.    if i%2 != 0:
8.       if 2*num_list_rev[i]>9:
9.          double = double + 2*num_list_rev[i] - 9
10.        else:
11.           double = double + 2 * num_list_rev[i]
12.  else:
13.       single = single + num_list_rev[i]
*********************************************************************





I don't understand why I have to compare double with 9 and then reducing it by 9 in the line number 8 and 9 ?
Why so ? Giles nothing mentioned about it or maybe i missed it.
Could you explain ?




2 answers ( 0 marked as helpful)
Instructor
Posted on:

24 Feb 2022

0

Hey,

Thank you for your comment! We are very happy to hear that you enjoyed the course :)

Regarding your question, the reason this is done is as follows. According to the algorithm, you need to double certain digits. In the example that Giles gives in the video, two of these digits are 7 and 4. Double them and you get 14 and 8. The next step is to add their digits together, that is 1+4+8. Extracting the digits of 8 is easy - its simply 8 :) That is not the case for 14. The following line of code

if 2*num_list_rev[i]>9:

checks whether the double of the original number gives you a number larger than 9. If that is the case (such as 7*2 = 14), then the following line is exetuted

double = double + 2*num_list_rev[i] - 9

which, in our example, corresponds to
double = double + 2*7 - 9 = double + 14 - 9 = double + 5
The 5 in the end is the sum of 1 and 4.

Subtracting 9 from a number in the range [10, 19] will always give you the sum of the digits. This, of course, would not work for larger numbers but in this exercise, we are not going to deal with numbers larger than 18.

Hope this answers your question! Keep up the good work!

Kind regards,
365 Hristina

Posted on:

24 Feb 2022

0

Hey !
Thank you for such a crisp explanation.
I really appreciate the effort you put to explain and lastly sorry, as It was my fault . I missed this point from video.

Submit an answer