Painless Recursion
1 min readFeb 23, 2023
Tips: Break the problem down into smaller problems and define the atomic solution.
The bigger task depends on some smaller task of the same/similar nature. Then delegate the task to those. In the end, there must be an atomic task that doesn’t depend on anyone else.
Say, you want to build an 11 storied building. You can only build the 10th floor when the 9th floor is done. You can only build the 9th floor when the 8th floor is done and so on.
def construct_building(floor_no):
if floor_no == -1:
return
print("Trying to construct " + str(floor_no))
construct_building(floor_no - 1)
print("Constructing " + str(floor_no))
Reverse a number
The value of the position just gets reversed. So, while modding, the last item to get out will get digit_position = 0
def reverse_num(num):
last_digit = num % 10
if last_digit == num:
digit_position = 0
return digit_position, last_digit
digit_position_less_one, total_so_far = reverse_num(num // 10)
digit_position = digit_position_less_one + 1
current_pos_value = 10 ** digit_position * last_digit
total_so_far += current_pos_value
return digit_position, total_so_far
print(reverse_num(5978))