`def weightedAverage(valueWeightList):`

'''

Takes a list of tuples (value, weight) and

returns weighted average as calculated by

Sum of all values * weights / Sum of all weights

'''

numerator = sum([v * w for v,w in valueWeightList])

denominator = sum([w for v,w in valueWeightList])

if(denominator != 0):

return(float(numerator) / float(denominator))

else:

return None

## 14.8.10

### Simple Weighted Average with Python

While I suspect there must already be a built in weighted average tool in some python library ( scipy / numpy), for a project I'm working on I just wrote my own. I would love to hear what people think and if I can improve the function in any way.

Subscribe to:
Post Comments (Atom)

Nice and simple, although you don't need the list comprehension square brackets any more (unless you need to support older versions of Python). Thanks!

ReplyDeleteHey no problem. Unfortunately I'm still stuck in the 2.x Python world :(

ReplyDelete