Solution Review: Average of Numbers
This review provides a detailed analysis of the solution to find the average of numbers.
We'll cover the following
Solution: Using Recursion
def average(testVariable, currentIndex = 0) :# Base Caseif currentIndex == len(testVariable) - 1 :return testVariable[currentIndex]# Recursive case1# When currentIndex is 0, divide sum computed so far by len(testVariable).if currentIndex == 0 :return ((testVariable[currentIndex] + average(testVariable, currentIndex + 1)) / len(testVariable))# Recursive case2# Compute sumreturn (testVariable[currentIndex] + average(testVariable, currentIndex + 1))# Driver codearr = [10, 2, 3, 4, 8, 0]print(average(arr))
Explanation
If we have numbers where each number is denoted by , the average is the of the numbers divided by or;
The average of an array containing only number, is the number itself. This condition can be our base case.
For the recursive case we have two conditions:
-
If the
currentIndex == 0
.- This means that we have accumulated the sum of all the numbers of the array so we can finally divide the total sum with the length of the array.
-
If the
currentIndex != 0
.- This means that we continue accumulating the sum of the numbers of the array.
In each recursive call we move the currentIndex
one step ahead.
In short, in each recursive call we reduce the length of the array. When length of the array reaches , we start adding all the numbers in the reverse order. When we have added all the numbers, in the last step ,i.e. when currentIndex == 0
, we divide the total sum by the length of the array.
Let’s have a look at the sequence of function calls for this example:
Let’s conquer another challenge in the next lesson.