4. Say Digit
In [21]:
Copied!
def say_digit(n, mapping):
"""
Example of head recursion
5321 -> Five Three Two One
"""
# 1. Base case
# when the number is over, 0 is left
# if you reach 0, return 0
if n == 0:
return 0
# 2. Processing
# extract the last digit
digit = n % 10
# 3. Recurrence relation
# remove the last digit from the original number
# till it is reduced to 0
n = say_digit(n // 10, mapping)
# when you hit the base case
# that is when this print statement will be called
# for the first time
print(mapping[digit])
def say_digit(n, mapping):
"""
Example of head recursion
5321 -> Five Three Two One
"""
# 1. Base case
# when the number is over, 0 is left
# if you reach 0, return 0
if n == 0:
return 0
# 2. Processing
# extract the last digit
digit = n % 10
# 3. Recurrence relation
# remove the last digit from the original number
# till it is reduced to 0
n = say_digit(n // 10, mapping)
# when you hit the base case
# that is when this print statement will be called
# for the first time
print(mapping[digit])
In [22]:
Copied!
mapping = {
0: "zero",
1: "one",
2: "two",
3: "three",
4: "four",
5: "five",
6: "six",
7: "seven",
8: "eight",
9: "nine",
}
mapping = {
0: "zero",
1: "one",
2: "two",
3: "three",
4: "four",
5: "five",
6: "six",
7: "seven",
8: "eight",
9: "nine",
}
In [23]:
Copied!
say_digit(5321, mapping)
say_digit(5321, mapping)
five three two one
In [1]:
Copied!
def say_digit_reverse(n, mapping):
"""
Example of tail recursion
"""
# 1. Base case
if n == 0:
return 0
# 2. Processing
# extract digit
digit = n % 10
# print the extracted digit right away
# before going to recursive call
print(mapping[digit])
# 3. Recursive relation
n = say_digit_reverse(n // 10, mapping)
def say_digit_reverse(n, mapping):
"""
Example of tail recursion
"""
# 1. Base case
if n == 0:
return 0
# 2. Processing
# extract digit
digit = n % 10
# print the extracted digit right away
# before going to recursive call
print(mapping[digit])
# 3. Recursive relation
n = say_digit_reverse(n // 10, mapping)
In [2]:
Copied!
mapping = {
0: "zero",
1: "one",
2: "two",
3: "three",
4: "four",
5: "five",
6: "six",
7: "seven",
8: "eight",
9: "nine",
}
say_digit_reverse(5321, mapping)
mapping = {
0: "zero",
1: "one",
2: "two",
3: "three",
4: "four",
5: "five",
6: "six",
7: "seven",
8: "eight",
9: "nine",
}
say_digit_reverse(5321, mapping)
one two three five 0 None None None
In [ ]:
Copied!