計算平均值
我們都知道要如何用迭代方式計算平均值:
def average(nums):
result = 0
for num in nums:
result += num
return result/len(nums)
你能提供一個遞迴的解法嗎?以下這個在加入新輸入時更新平均值的公式會很實用:
$$ \bar{x} \leftarrow \frac{x_i + (n-1)\bar{x}}{n} $$
其中,\(\bar x\) 是目前的平均值,\(x_i\) 是用來更新平均的新數值,\(n\) 對應到遞迴呼叫的次數(不包含對函式的最初呼叫)。
本練習屬於課程
Python 程式面試題實作練習
練習說明
- 定義演算法的基底情況(base case)。
- 定義用於更新平均值的遞迴呼叫。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# 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]))