'how to reduce a list of tuples, return a concrete number
I was wondering what is wrong with my code, it now has a typeError: 'float' object is not subscriptable
# this function is to calculate Weighted Average Maturity of the mortgage pool
# pass in a list of mortgages (amount, rate, terms)
def WAM(tup):
return reduce(WAM_SUM, tup)
def WAM_SUM(x, y):
return (x[0] * (x[2]/12) + y[0] * (y[2]/12)) / (x[0] + y[0])
the list of tuple will be passing in is something like this (first one is amount, and the third one is term): [(208000, 0.015, 120), (156000, 0.03, 180), (720000, 0.065, 240), (333000, 0.087, 120), (241000, 0.0315, 240)]
I would like to use reduce to make it plays the same functionality as below:
def weightedAM(tup):
sum_val = sum(amount for amount, rate, term in tup) #sum up all the loan amount
wam_sum = sum((amount / sum_val) * (term / 12) for amount, rate, term in tup)
return wam_sum
Solution 1:[1]
instead of doing one reduce, I would do two now, and it works
def WAM(tup):
return reduce(WAM_SUM, tup, 0) / reduce(Amount_SUM, tup, 0)
def WAM_SUM(total, tup):
return total + (tup[0] * (tup[2] / 12))
def Amount_SUM(total, tup):
return total + tup[0]
also I could use lambda:
def WAM_L(tup):
return reduce(lambda total, WAM_SUM1: total + (WAM_SUM1[0] * (WAM_SUM1[2] / 12)), tup, 0) / \
reduce(lambda total, Amount_SUM1: total + Amount_SUM1[0], tup, 0)
However, in terms of code clarity and readability, I do think the original one is better than reduce
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | czzz0414 |
