Sunday, October 1, 2017

Python Map Reduce on Tuple List

I was recently asked to read some pseudocode for calculating a class average of weighted scores. I wanted to work this out in Python to demonstrate how the design decisions around data structures impact implementation. Two independent lists assume order is maintained properly in two places. However it makes the code easier to explain.

flatScores = [75,95,85,65]
weights = [0.2,0.35,0.15,0.3]

def mult(x,y): return x * y
# map(mult,flatScores,weights)
# [15.0, 33.25, 12.75, 19.5]
reduce((lambda sum,score: (sum + score) ),list(map(mult,flatScores,weights)))/len(flatScores)
#20.125

A single list of tuples allows members to include all relevant data in one place. 

scores = [[75,0.2],[95,0.35],[85,0.15],[65,0.3]]
def mapper(scoreWeights): return map( lambda scoreWeight: scoreWeight[0] * scoreWeight[1] , scoreWeights )
# mapper(scores)
# [15.0, 33.25, 12.75, 19.5]
reduce(lambda sum, cur: sum + cur, mapper(scores))/len(scores)
#20.125