PwNzDust
PwNzDust

Reputation: 281

Recursive code to find weighted mean value ​

Develop a Python function ​ foo(l) that given a list ​ l of numbers returns the weighted mean value ​ w ​ that for a1,a2...an is defined as:

enter image description here

The function ​ wavg(l) may use other sub-functions if needed. At least one developed function ​ must be recursive. ​

My implementation is the following, but i do not know if i have correctly interpreted the summation formula:

def wavg(L):
    if len(L) == 1:
        return L[0]/len(L)
    else:
        return L[len(L)-1]/len(L) + wavg(L[:-1])

Upvotes: 0

Views: 365

Answers (1)

Daniel Qvistgaard
Daniel Qvistgaard

Reputation: 46

It looks fine for me. Consider an example:

L = [5,5,5]

By running your function, I get 9.166.

If we do the math, the calculation is

5/1 + 5/2 + 5/3 = 5 + 2.5 + 1.66 = 9.166

So to answer your question, yes, you have correctly interpreted the summation.

Upvotes: 1

Related Questions