K
K
Kollapser2021-04-14 12:57:44
Python
Kollapser, 2021-04-14 12:57:44

How to find the arithmetic mean of array elements through recursion?

Wrote this, but there must be a more elegant way

test_list = [1, 4, 7]

def func(list1, a=0, b=0):
  if list1 == []:
    return 0

  b += list1[a]
  a += 1

  if a == len(list1):
    return b / a
  return func(list1, a, b)

print(func(test_list))

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2021-04-14
@wataru

Think about how you can recursively calculate the sum. Further, the arithmetic mean is elementarily expressed in terms of the sum, and the sum is expressed in terms of the arithmetic mean. Here is the formula:
Avg(a1,a2,...an) = (Avg(a2,...an)*(n-1)+a1)/n

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question