Search⌘ K
AI Features

Solution Review: Average of Numbers

Explore how to use recursion to calculate the average of numbers in an array by breaking down the problem into base and recursive cases. Understand the method of accumulating sums through recursive calls and dividing by the array length once all elements are processed. This lesson helps you master recursive thinking applied to arrays for coding interviews.

We'll cover the following...

Solution: Using Recursion

Python 3.5
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

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 \: ...