2️⃣

18.2 Base Case and Recursive Case

Base Case and Recursive Case

The base case(s) is the condition that causes the function to stop calling itself.
The recursive case(s) is the condition that allows the function to call itself.
Let’s go back to the example from the previous section which was figuring out how many of a factor a number has. Let’s use 24 as our number again and 2 as the factor again. The base case in this example is if the current number is no longer divisible by 2. If the function is at the base case, the number of 2’s that are divided to get the current number is returned. The recursive case in this example is if the current number is still divisible by 2. If the function is in the recursive case, the current number is divided by 2 and the number of 2’s divided so far is incremented by one. These parameters will be used to call itself (the function) again.
Remember, the recursive case will repeat itself until the base case is reached.
If you know the base case(s) and the recursive case(s) for this recursion problem, you can easily write the code for this recursion problem. Here is the code from the example we just talked about:
# Code to figure out how many of a factor a number has def number_factor(number, factor, factor_counter = 0): """ Parameters: 1) number is the number in which we are finding the number of factors of. EX: 24 2) factor is the factor in which we are finding the number of in the parameter number. EX: 2 Output: The number of times the parameter number can be divisible by the parameter factor. This number is also the parameter factor_counter right before it is returned. EX: 3 """ if number % factor != 0: # Base Case return factor_counter else: # Recursive Case return number_factor(number / factor, factor, factor_counter + 1) print(number_factor(24, 2))
View code on GitHub.
There can be many base cases and/or recursive cases. You will learn about this in later sections.
 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.