BaşlayınÜcretsiz başlayın

Calculate an average value

We all know how to calculate an average value iteratively:

def average(nums):

    result = 0

    for num in nums:
        result += num

    return result/len(nums)

Could you provide a recursive solution? A formula for updating an average value given a new input might be handy:

$$ \bar{x} \leftarrow \frac{x_i + (n-1)\bar{x}}{n} $$

Here, \(\bar x\) stands for an average value, \(x_i\) is a new supplied value which is used to update the average, and \(n\) corresponds to the recursive call number (excluding the initial call to the function).

Bu egzersiz, kursun bir parçasıdır

Practicing Coding Interview Questions in Python

Kursa Göz Atın

Egzersiz talimatları

  • Provide the base case for the algorithm.
  • Define the recursive call for updating the average value.

Uygulamalı etkileşimli egzersiz

Bu egzersizi bu örnek kodu tamamlayarak deneyin.

# Calculate an average value of the sequence of numbers
def average(nums):
  
    # Base case
    if len(nums) == ____:  
        return ____[____]
    
    # Recursive call
    n = len(nums)
    return (____ + ____ * ____) / ____

# Testing the function
print(average([1, 2, 3, 4, 5]))
Kodu Düzenle ve Çalıştır