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

Press + to interact
def average(testVariable, currentIndex = 0) :
# Base Case
if 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 sum
return (testVariable[currentIndex] + average(testVariable, currentIndex + 1))
# Driver code
arr = [10, 2, 3, 4, 8, 0]
print(average(arr))

Explanation

If we have nn numbers where each number is denoted by aia_i (wherei=0,1,2,...,n1)(where \: i = 0, 1, 2, ..., n-1), the average is the sumsum of the numbers divided by nn or;

average=1ni=0n1ai=a0+a1+a2++an1n{\displaystyle average={\frac {1}{n}}\sum _{i=0}^{n-1}a_{i}={\frac {a_{0}+a_{1}+a_{2}+\cdots +a_{n-1}}{n}}}

The average of an array containing only 11 number, is the number itself. This condition can be our base case.

averageofarrayoflength1=a01=a0\displaystyle average \: of \: array \: of \: length \: 1={\frac {a_{0}}{1}} = a_{0}

For the recursive case we have two conditions:

  1. 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.
  2. 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 11, 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.