On 02/09/2010 21:37, Baba wrote:
level: beginner
exercise source:
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset4.pdf
Problem 4
Can my code be optimised?
I think my approach is correct but i am hesitant about the initial max
value.
def nestEgVariable(salary, save, preRetireGrowthRates):
SavingsRecord = []
fund = 0
depositPerYear = salary * save * 0.01
for i in preRetireGrowthRates:
fund = fund * (1 + 0.01 * i) + depositPerYear
SavingsRecord += [fund,]
startingPot = SavingsRecord[-1]
return startingPot
Why are you saving 'fund' in SavingsRecord if you're returning just the
last and discarding others? Basically you're returning the final value
of fund.
def
expenseCalculator(postRetireGrowthRates,fundsize,epsilon,yearsOfretirement ):
low = 0
high = fundsize
guess = (low + high) /2
while abs(guess * yearsOfretirement - fundsize)> epsilon:
if guess * yearsOfretirement> fundsize :
high = guess
else: low = guess
guess = (low + high) /2
return guess
When performing this type of 'search' make sure that the interval (high
- low) reduces at every step. If, for example:
low + 1 == high
then:
guess == (low + (low + 1)) / 2 == (low * 2 + 1) / 2 == low
(integer division) and if the 'if' condition happens to be false then
the value of 'low' won't change for the next iteration, leading to an
infinite loop.
def findMaxExpenses(salary,save,preRetireGrowthRates,
postRetireGrowthRates,epsilon):
yearsOfretirement = len(postRetireGrowthRates)
fundsize = nestEgVariable(salary, save, preRetireGrowthRates)
for growthRate in postRetireGrowthRates:
expenses = expenseCalculator(postRetireGrowthRates,
fundsize ,epsilon,yearsOfretirement )
fundsize = (fundsize * (1 + 0.01 * growthRate)) - expenses
print 'fundsize', fundsize
print 'expenses', expenses
yearsOfretirement -=1
return fundsize
findMaxExpenses(10000,10,[3, 4, 5, 0, 3],[10, 5, 0, 5, 1],0.01)
--
http://mail.python.org/mailman/listinfo/python-list