-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLecture_7
73 lines (42 loc) · 1.35 KB
/
Lecture_7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
Definition:
Recursive function: a function is called recursive if the body of that function calls itself, either directly or indirectly.
A useful algorithm:
def split(n):
return n // 10, n % 10
def sum_digits(n):
if n < 10:
return n
else:
all_but_last, last = split(n)
return sum_digits(all_but_last) + last
>>> sum_digits(123)
6
Another example of factorial:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
>>> factorial(3)
6
Note: iteration is a special case of recursion.
Now we need to study the Luhn algorithm. This algorithm applies widely in checking credit card numbers. That is, it will double every digits of the credit card number, if the product is greater than 9, then replace it with the sum of its digits. At last find the sum of the transformed digits.
def sum_digits(n):
if n < 10:
return n
else:
all_but_last, last = split(n)
return sum_digits(all_but_last) + last
def luhn_sum(n):
if n < 10:
return n
else:
all_but_last, last = split(n)
return luhn_sum_double(all_but_last) + last
def luhn_sum_double(n):
all_but_last, last = split(n)
luhn_digit = sum_digits(2 * last)
if n < 10:
return luhn_digit
else:
return luhn_sum(all_but_last) + luhn_digit