Stop learning alone!

Learn faster and stay on-track by joining this free class with other self-learners.

Register for MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming now.

MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming

Class length: 24 weeks. Start anytime.

Creator: duallain

Status: Established

Join this class!

Lesson 7: Assignment 1

Assignment 4: Simulating a retirement fund

Homework Submissions

31 total

smiller148 (Self-grade: Pretty good)
Submitted 2 weeks ago | Permalink | Time spent: 1 day
# Problem Set 4
# Name: smiller148
# Collaborators: eventually, curiousreef submissions for #1.
# Time: a few days, including the debugging period

#
# Problem 1
#

def nestEggFixed(salary, save, growthRate, years):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an
      integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at
      the end of each year.
    """
    outputList=[]
    acctTotal=0
    for i in range(0,years):
        contribution=salary*save*0.01
        compounding=acctTotal*(1+growthRate*0.01)
        acctTotal=contribution+compounding # charmed by the simplicity of the range construction that repeats this for the specified number of years
        outputList.append(acctTotal) # initially thought an exponential was necessary-no!
    return outputList
    
# And a functional test case, for fun:

def test1NestEggFixed():
    salary     =50000
    save       =12
    growthRate =5
    years      =30
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord

#
# Problem 2
#

def nestEggVariable(salary, save, growthRates):
    outputList=[]
    acctTotal=0
    for i in growthRates: # stepping through the list and calculating acctTotal increases for rates associated with different years
        contribution=salary*save*0.01
        compounding=acctTotal*(1+i*0.01) # critical:must refer to specific rate in list, i
        acctTotal=contribution+compounding
        outputList.append(acctTotal)
    return outputList
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
      account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """

# Ok, a test case-let's say a well-compensated job in a low cost of living region, modest stock returns:

def test1nestEggVariable():
    salary      = 100000
    save        = 25
    growthRates = [3, 4, 5, 0, 3]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord

#
# Problem 3
#
# a very quick modification to problem 2 code:

def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
      account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
      retirement.
    - return: a list of your retirement account value at the end of each year.
    """
    outputList=[]
    acctTotal=savings
    for i in growthRates: # stepping through the list and calculating acctTotal increases for rates associated with different years
        compounding=acctTotal*(1+i*0.01) # critical:must refer to specific rate in list, i
        acctTotal=compounding-expenses
        outputList.append(acctTotal)
    return outputList


# Test case: 15 years-hoping these retirees have low medical bills:

def test1PostRetirement():
    savings     = 500000
    growthRates = [10, 5, 0, 5, 1, 2, 3, 2, 5, 1, 1, 1, 0, 0, 2]
    expenses    = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord

# so good that there's still $220K in the bank for them, unless they live to 100.

#
# Problem 4
#
# Pleased to report no help in debugging this one:

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,
                    epsilon):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments
      while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments
      while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in
      the investment fund at the end of retirement.
    """

    acctTotal=0
    for i in preRetireGrowthRates:
        contribution=salary*save*0.01
        compounding=acctTotal*(1+i*0.01) 
        acctTotal=contribution+compounding
    totalSavings=acctTotal
    expLow=0
    expHigh=totalSavings+epsilon
    expGuess=(expLow+expHigh)/2.0
    postRetireList=[]
    finalBalance=totalSavings
    print totalSavings
    while abs(finalBalance) > epsilon:
        balance=totalSavings
        for j in postRetireGrowthRates:
            compounding=balance*(1+j*0.01) 
            balance=compounding-expGuess
            postRetireList.append(balance)
        finalBalance=postRetireList[-1]
        print 'Final balance:', finalBalance,'  Expense estimate:',expGuess
        if finalBalance > 0:# expGuess was too low; money left over->find a higher expense 
            expLow = expGuess
        else:                       # expGuess was too high; too large final debt->find a lower expense
            expHigh = expGuess
        expGuess = (expLow+expHigh)/2.0
    print 'Yearly expense estimate:'
    return expGuess
                
def test1FindMaxExpenses():
    salary                = 250000
    save                  = 50
    preRetireGrowthRates  = [3, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0, 5, 1, 2, 3, 2, 5, 1, 1, 1, 0, 0, 2]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses
    # Output here generates a value close to:
    # 56849.595...for a 15-year retirement, no saving until the last 5 years of work,
    # but high salary, high savings rate.

 
 #   while abs(totalSavings-finalBalance) > epsilon:   ## This line calculates a yearly expense total that would preserve 100% of principal.
ChapLeo (Self-grade: Outstanding)
Submitted 2 months ago | Permalink | Time spent: 3 hours

This problem-set was pretty easy!

# Problem Set 4
# Name: Chapman
# Collaborators: None
# Time: 3:15

#
# Problem 1
#

def nestEggFixed(salary, save, growthRate, years):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an
      integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at
      the end of each year.
    """
    assert years>0, 'Number of years should be greater than 0'   #verifies that no. of years is greater than 0
    retireFund=[]
    currValue=0
    for year in range (0,years):           #iterates for each year upto number of years given in 'years' variable
        if year==0:                     
            retireFund.append(salary * save * 0.01)     #if it is the first year, growth rate is not calculated, only the money put into fund is calculated.
        else:
            retireFund.append(retireFund[-1] * (1 + 0.01 * growthRate) + (salary * save * 0.01))   #for all other years, money put into fund and growth rate is calculated
    return retireFund                         #returns list containing size of fund at end of each year


def testNestEggFixed():
    salary     = 10000
    save       = 10
    growthRate = 15
    years      = 5
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2150.0, 3472.5, 4993.375, 6742.3812499999995]

    # TODO: Add more test cases here.

#
# Problem 2
#

def nestEggVariable(salary, save, growthRates):
    
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
      account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """

    assert growthRates != [], 'No growthRate data is given!'     #veries 'growthRates' list is NOT empty
    retireFund=[salary * save * 0.01]                       #for 1st year, only the money put into the fund is claculated. Growth rate is not claculated
    for element in growthRates[1:]:                         #iterates for each element (staring from element 2) in growthRates list by assigning the current element to the 'element' variable
            retireFund.append(retireFund[-1] * (1 + 0.01 * element) + (salary * save * 0.01))   #for each year after 1st, both growth rate and money put into fund are calculated
        
    return retireFund        #returns list containing elements corresponding to size of fund at end of each year



def testNestEggVariable():
    salary      = 10000
    save        = 10
    growthRates = [3, 4, 5, 0, 3]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002]

    # TODO: Add more test cases here.

#
# Problem 3
#

def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
      account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
      retirement.
    - return: a list of your retirement account value at the end of each year.
    """
    
    assert growthRates != [], 'No growthRate data given!'        #veries 'growthRates' list is NOT empty
    amountLeft= [(savings * (1 + 0.01 * growthRates[0])) - expenses]     #for the first year, the initail amount in fund: 'savings' is used for calculation
    for element in growthRates[1:]:                                                     #iteration begins at 2nd element in the growthRates list 
        amountLeft.append((amountLeft[-1] * (1 + 0.01 * element)) - expenses)       #for each year after,the preceeding amount in the fund is used for calulation
    return amountLeft                           #returns a list containing the amount of money left in fund at end of each year



def testPostRetirement():
    savings     = 100000
    growthRates = [10, 5, 0, 5, 1]
    expenses    = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord
    # Output should have values close to:
    # [80000.000000000015, 54000.000000000015, 24000.000000000015,
    # -4799.9999999999854, -34847.999999999985]

    # TODO: Add more test cases here.

#
# Problem 4
#

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,
                    epsilon):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments
      while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments
      while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in
      the investment fund at the end of retirement.
    """

    preRetireList = nestEggVariable(salary, save,preRetireGrowthRates) #growth of fund until retirement is calculated
    high = preRetireList[-1]    #money in fund at start of retirement is the upper bound
    low = 0                     #0 is assigned as the lower bound
    guess = (high + low)/2.0         #guess is the average of lower and upper bound
    postRetireList = postRetirement(preRetireList[-1],postRetireGrowthRates,guess)   #shrinking of fund after retirement is calculated
    print guess          #guess is printed
     
    while abs(postRetireList[-1]) >= epsilon:   #iterates while the size of fund at last year after retirement is not equal(error of epsilon) to 0
        if postRetireList[-1] < 0:      #if the last year after retirement results in a deficit, upper bound is decreased to 'guess' variable
            high = guess
        else:
            low = guess             #else, the lower bound is increased to 'guess' variable
        guess = (high + low)/2.0     #process is repeated: avgerage caculated, postRetirement calculated....
        postRetireList = postRetirement(preRetireList[-1],postRetireGrowthRates,guess)
        print guess
    ans = 'Your annual expenses should be: ' + str(guess)       #at end of loop, the string containing the ideal 'expense' is returned
    return ans


def testFindMaxExpenses():
    salary                = 10000
    save                  = 10
    preRetireGrowthRates  = [3, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0, 5, 1]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses
    # Output should have a value close to:
    # 1229.95548986
biant92 (Self-grade: Outstanding)
Submitted 3 months ago | Permalink | Time spent: 4 days
# Problem Set 4
# Name: Rajko Vujic
# Collaborators: CuriousReef website
# Time: A few days

#
# Problem 1
#

def nestEggFixed(salary, save, growthRate, years):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an
      integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at
      the end of each year.
    """
    firstYear = salary * save * 0.01
    annualGrowth = 1 + 0.01 * growthRate
    retirementFund = []
    retirementFund.append(firstYear)
    n = 1
    while n < years:
        retirementFund.append(retirementFund[n - 1] * annualGrowth + firstYear)
        n += 1
    return retirementFund


def testNestEggFixed():
    salary     = 10000
    save       = 10
    growthRate = 15
    years      = 5
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2150.0, 3472.5, 4993.375, 6742.3812499999995]

    # TODO: Add more test cases here.
    salary      = 20000
    save        = 15
    growthRate  = 15
    years       = 10
    savingsRecordA = nestEggFixed(salary, save, growthRate, years)
    print savingsRecordA


#
# Problem 2
#

def nestEggVariable(salary, save, growthRates):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
      account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """
    firstYear = salary * save * 0.01
    retirementFund = []
    retirementFund.append(firstYear)
    years = len(growthRates)
    n = 1
    while n < years:
        annualGrowth = 1 + 0.01 * growthRates[n]
        retirementFund.append(retirementFund[n - 1] * annualGrowth + firstYear)
        n += 1
    return retirementFund


def testNestEggVariable():
    salary      = 10000
    save        = 10
    growthRates = [3, 4, 5, 0, 3]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002]

    # TODO: Add more test cases here.
    salary      = 20000
    save        = 15
    growthRates = [5, 4, 7, 0, 3, 6, 10, 11, 1, 8]
    savingsRecordA = nestEggVariable(salary, save, growthRates)
    print savingsRecordA


#
# Problem 3
#

def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
      account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
      retirement.
    - return: a list of your retirement account value at the end of each year.
    """
    firstYear = savings * (1 + 0.01 * growthRates[0]) - expenses
    retirementFund = []
    retirementFund.append(firstYear)
    n = 1
    while n < len(growthRates):
        annualGrowth = 1 + 0.01 * growthRates[n]
        retirementFund.append(retirementFund[n - 1] * annualGrowth  - expenses)
        n += 1
    return retirementFund


def testPostRetirement():
    savings     = 100000
    growthRates = [10, 5, 0, 5, 1]
    expenses    = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord
    # Output should have values close to:
    # [80000.000000000015, 54000.000000000015, 24000.000000000015,
    # -4799.9999999999854, -34847.999999999985]

    # TODO: Add more test cases here.
    savings     = 50000
    growthRates = [2, 3, 4, 5, 6, 3, 4, 6, 4, 5]
    expenses    = 10000
    savingsRecordA = postRetirement(savings, growthRates, expenses)
    print savingsRecordA
    


#
# Problem 4
#

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,
                    epsilon):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments
      while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments
      while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in
      the investment fund at the end of retirement.
    """
    savings = nestEggVariable(salary, save, preRetireGrowthRates)[-1]
    low = 0
    high = savings
    guess = (low + high)/2.0
    ctr = 1
    while abs (postRetirement(savings, postRetireGrowthRates, guess)[-1]) > epsilon and ctr <= 100:
        if postRetirement(savings, postRetireGrowthRates, guess)[-1] > epsilon:
            low = guess
        else:
            high = guess
        guess = (low + high)/2.0
    assert ctr <= 100, 'Iteration count exceeded'        
    return guess



def testFindMaxExpenses():
    salary                = 10000
    save                  = 10
    preRetireGrowthRates  = [3, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0, 5, 1]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses
    # Output should have a value close to:
    # 1229.95548986

    # TODO: Add more test cases here.
    salary                  = 100000
    save                    = 15
    preRetireGrowthRates    = [2, 3, 4, 0, 2, 4, 5, 0, 4, 6]
    postRetireGrowthRates   = [9, 4, 0, 4, 0, 2, 3, 4, 0, 2]
    epsilon                 = .02
    expensesA = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expensesA
fhalo (Self-grade: Could be better)
Submitted 4 months ago | Permalink | Time spent: 48 days
# Problem Set 4
# Name: Fhalo
#
# Collaborators: None
# Time: 
#
# Date Start: 02-Sep-2012
#
# Problem 1
#

# Problem Set 4
# Name: Fhalo
#
# Collaborators: None
# Time: 1.00h
#
# Date Start: 15/12/12
#
# Problem 2
#

def nestEggVariable(salary, save, growthRates):
    # TODO: Your code here.
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
      account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """
    investment = []
    
    year0 = salary * save * 0.01
    year1 = year0 * (1 + 0.01 * growthRates[0]) + salary * save * 0.01
    year2 = year1 * (1 + 0.01 * growthRates[1]) + salary * save * 0.01
    year3 = year2 * (1 + 0.01 * growthRates[2]) + salary * save * 0.01
    year4 = year3 * (1 + 0.01 * growthRates[3]) + salary * save * 0.01
    year5 = year4 * (1 + 0.01 * growthRates[4]) + salary * save * 0.01
    
    investment.append(year0)
    investment.append(year1)
    investment.append(year2)
    investment.append(year3)
    investment.append(year4)
    investment.append(year5)
    
    return investment

    
def testNestEggVariable():
    salary      = 10000
    save        = 10
    growthRates = [3, 4, 5, 0, 3]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002]

    # TODO: Add more test cases here.

#

testNestEggVariable()



# Problem Set 4
# Name: Fhalo
#
# Collaborators: None
# Time: 20min
#
# Date Start: 16/12/12
#
# Problem 3
#

def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
      account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
      retirement.
    - return: a list of your retirement account value at the end of each year.
    """
    # TODO: Your code here.
    
    investment = []
    
    fund0 = savings  * (1 + 0.01 *  growthRates[0]) - expenses
    fund1 = fund0  * (1 + 0.01 *  growthRates[1]) - expenses
    fund2 = fund1  * (1 + 0.01 *  growthRates[2]) - expenses
    fund3 = fund2  * (1 + 0.01 *  growthRates[3]) - expenses
    fund4 = fund3  * (1 + 0.01 *  growthRates[4]) - expenses
    
    investment.append(fund0)
    investment.append(fund1)
    investment.append(fund2)
    investment.append(fund3)
    investment.append(fund4)
    
    return investment


def testPostRetirement():
    savings     = 100000
    growthRates = [10, 5, 0, 5, 1]
    expenses    = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord
    # Output should have values close to:
    # [80000.000000000015, 54000.000000000015, 24000.000000000015,
    # -4799.9999999999854, -34847.999999999985]

    # TODO: Add more test cases here.


testPostRetirement()


# Problem Set 4
# Name: Fhalo
#
# Collaborators: Help from https://github.com/sebrenner/Mit-6.00-OCW-Problem-Set-Solutions
# Time: 20min
#
# Date Start: 16/12/12
#
# Problem 4
#

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,
                    epsilon):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments
      while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments
      while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in
      the investment fund at the end of retirement.
    """
    # TODO: Your code here.
    
    # Start with a range of possible values for your expenses
    # between 0 and your savings at the start of your retirement.
    low = 0
    
    # Set the high guess to value of the nest egg at moment
    # of retirement or 1, which ever higher
    high = max(nestEggVariable(salary, save, preRetireGrowthrates)[-1],1)
    
    
    balanaceAtRetirement = nestEggVariable(salary, save, preRetireGrowthRates)[-1]
    
    # Bisect the range between high and low and initialize the guess to this value
    guess = (low + high)/2
    
    ctr = 1
    
    # Set the remaining balance to the balance at the end of retirement (death?).
    remainingBalance = postRetirement(balanceAtRetirement, postRetireGrowthRates, guess)
    
    while abs(remainingBalanace) > epsilon and ctr <= 100:
        if remainingBalance < 0:
            high = guess
        else:
            low = guess
        ctr += 1
        guess = (low + high)/2
        remainingBalance = postRetirement(balanceAtRetirement, postRetireGrowthrates, guess)
    assert ctr <= 100, 'Itration count exceeded'
    return guess

def testFindMaxExpenses():
    salary                = 10000
    save                  = 10
    preRetireGrowthRates  = [3, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0, 5, 1]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses
    # Output should have a value close to:
    # 1229.95548986

    # TODO: Add more test cases here.


testPostRetirement()









def nestEggFixed(salary, save, growthRate, years):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an
      integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at
      the end of each year.
    """
    # TODO: Your code here.
    
    investment = []
    
    year0 = salary * save * 0.01
    year1 = year0 * (1 + 0.01 * growthRate) + salary * save * 0.01
    year2 = year1 * (1 + 0.01 * growthRate) + salary * save * 0.01
    year3 = year2 * (1 + 0.01 * growthRate) + salary * save * 0.01
    year4 = year3 * (1 + 0.01 * growthRate) + salary * save * 0.01
    
    
    investment.append(year0)
    investment.append(year1)
    investment.append(year2)
    investment.append(year3)
    investment.append(year4)
    
    return investment


def testNestEggFixed():
    salary     = 10000
    save       = 10
    growthRate = 15
    years      = 5
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2150.0, 3472.5, 4993.375, 6742.3812499999995]

    # TODO: Add more test cases here.
    
testNestEggFixed()
nickrt (Self-grade: Outstanding)
Submitted 11 months ago | Permalink | Time spent: 40 minutes

I probably should have tested it more, but oh well... At least I commented it this time.

Oh and I did this before lecture 7 so I will edit it if anything changes, if this message is still here I didn't edit it

# Problem Set 4
# Name: Nick
# Collaborators: None
# Time: 0:40

#
# Problem 1
#

def nestEggFixed(salary, save, growthRate, years):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an
      integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at
      the end of each year.
    """
    fund = [salary*save*.01] #Initial funds after first year
    for i in range(1, years):#Changing the funds every year based on the previous term in the list and savings
        fund.append(fund[i-1]*(1+.01*growthRate)+salary*save*.01)
    return fund#returns final amount saved
    
def testNestEggFixed():
    salary     = 10000
    save       = 10
    growthRate = 15
    years      = 5
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2150.0, 3472.5, 4993.375, 6742.3812499999995]

    # TODO: Add more test cases here.

#
# Problem 2
#

def nestEggVariable(salary, save, growthRates):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
      account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """
    fund = [salary*save*.01]#Initial savings after first year

    #This part calculates the final funds after the set number of years have passed
    #fund is i-1 because you are looking at the previous term, and growth rate is i
    #because you are looking at that term
    for i in range(1,len(growthRates)):
        fund.append(fund[i-1]*(1+.01*growthRates[i])+salary*save*.01)
    return fund

def testNestEggVariable():
    salary      = 10000
    save        = 10
    growthRates = [3, 4, 5, 0, 3]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002]

    # TODO: Add more test cases here.

#
# Problem 3
#

def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
      account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
      retirement.
    - return: a list of your retirement account value at the end of each year.
    """
    fund = [savings * (1+.01*growthRates[0]) - expenses] #Initial funds after 1 year of retirement

    #Same kind of thing as the last one but instead of
    #+ salary*save*.01 you have - expenses
    for i in range(1,len(growthRates)):
        fund.append(fund[i-1]*(1+.01*growthRates[i]) - expenses)
    return fund

def testPostRetirement():
    savings     = 100000
    growthRates = [10, 5, 0, 5, 1]
    expenses    = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord
    # Output should have values close to:
    # [80000.000000000015, 54000.000000000015, 24000.000000000015,
    # -4799.9999999999854, -34847.999999999985]

    # TODO: Add more test cases here.

#
# Problem 4
#

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,
                    epsilon):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments
      while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments
      while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in
      the investment fund at the end of retirement.
    """
    savingsRecord = nestEggVariable(salary, save, preRetireGrowthRates)
    initSavings = savingsRecord[-1]#finds the initial savings when you just finish working
    low = 0#sets low end of range
    high = initSavings + epsilon#sets high end of range
    guess = (low + high)/2.0#sets the guess 1/2 way between low and high
    savingsRecord = postRetirement(initSavings, postRetireGrowthRates, guess)
    savings = savingsRecord[-1]#Calculates how much you have left in account after using guess as yearly expenses
    counter = 1#counter to exit loop if too many iterations

    #This loop improves guess every time by cutting out the values lower than guess
    #if you had excess money, and cut out values higher than guess if you were in the red
    #Then it creates a new guess between the new low and high and calculates a new savings
    #left when you die and uses it to see if it is less than epsilon and if so exit loop, if not repeat
    while abs(savings) > epsilon and counter <= 100:
        if savings > 0:
            low = guess
        else:
            high = guess
        guess = (low+high)/2.0
        savingsRecord = postRetirement(initSavings, postRetireGrowthRates, guess)
        savings = savingsRecord[-1]
        counter += 1
    assert counter <= 100, 'Iteration count exceeded'
    return guess#Final answer

def testFindMaxExpenses():
    salary                = 10000
    save                  = 10
    preRetireGrowthRates  = [3, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0, 5, 1]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses
    # Output should have a value close to:
    # 1229.95548986

    # TODO: Add more test cases here.
sebrenner (Self-grade: Outstanding)
Submitted 1 year ago | Permalink | Time spent: 21 minutes
# Problem Set 4
# Name: 
# Collaborators: 
# Time: 

#
# Problem 1
# Start time: 2011-02-06 5:10 PM
# End time: 2011-02-06 5:31 PM
# Total time: 21 minutes.

# Write a function, called nestEggFixed, which takes four arguments: a salary, a percentage of your salary to save in an investment account, an annual growth percentage for the investment account, and a number of years to work. This function should return a list, whose values are the size of your retirement account at the end of each year, with the most recent year's value at the end of the list.

##  Complete the implementation of:
def nestEggFixed(salary, save, growthRate, years):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an
      integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at
      the end of each year.
    """
    # End of year 1 -->   F[0] = salary * save * 0.01
    # End of year 2 -->   F[1] = F[0] * (1 + 0.01 * growthRate) + salary * save * 0.01
    # End of year 3 --> F[2] = F[1] * (1 + 0.01 * growthRate) + salary * save * 0.01
    
    # TODO: Your code here.
    answer = [0]
    for each in range(0,years):
        #print each
        temp = answer[-1] * (1 + 0.01 * growthRate) + salary * save * 0.01
        answer.append(temp)
        #print answer
    del answer[0]
    return answer

def testNestEggFixed():
    salary     = 10000
    save       = 10
    growthRate = 15
    years      = 5
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2150.0, 3472.5, 4993.375, 6742.3812499999995]

    # TODO: Add more test cases here.
    salary     = 40000
    save       = 12
    growthRate = 7
    years      = 20
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord

    salary     = 80000
    save       = 12
    growthRate = 7
    years      = 20
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord

#   testNestEggFixed()  #Just for testing 

#
# Problem 2
#
# Start time: 2011-02-06 5:32 PM
# End time: 2011-02-06  5:41 PM
# Total time: 9 minutes.

# Write a function, called nestEggVariable, which takes three arguments: a salary (salary), a percentage of your salary to save (save), and a list of annual growth percentages on investments (growthRates). The length of the last argument defines the number of years you plan to work; growthRates[0] is the growth rate of the first year, growthRates[1] is the growth rate of the second year, etc. (Note that because the retirement fund's initial value is 0, growthRates[0] is, in fact, irrelevant.) This function should return a list, whose values are the size of your retirement account at the end of each year.


def nestEggVariable(salary, save, growthRates):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
      account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """
    # TODO: Your code here.
    answer = [0]
    for each in range(len(growthRates)):
        #print each
        temp = answer[-1] * (1 + 0.01 * growthRates[each]) + salary * save * 0.01
        answer.append(temp)
        #print answer
    del answer[0]
    return answer
    
def testNestEggVariable():
    salary      = 10000
    save        = 10
    growthRates = [3, 4, 5, 0, 3]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002]

    # TODO: Add more test cases here.
    salary      = 40000
    save        = 10
    growthRates = [3, 7, 8, 10, 3,7, 8, 10, 3,7, 8, 10, 3,7, 8, 10, 3]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord

    salary      = 80000
    save        = 10
    growthRates = [3, 0, 15, 0, 31,7, 8, 10, 3]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord

    salary      = 650000
    save        = 10
    growthRates = [7, 8, 10, 3, 7, 8, 10, 3, 13, 7, 8, 10, 3, 14, 15, 10, 13]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord

#testNestEggVariable() # Just for testing

#
# Problem 3
#
# Start time: 2011-02-06 5:46 PM
# End time: 2011-02-06 5:57 PM
# Total time:  11 minutes.

# Write a function, called postRetirement, which takes three arguments: an initial amount of money in your retirement fund (savings), a list of annual growth percentages on investments while you are retired (growthRates), and your annual expenses (expenses). Assume that the increase in the investment account savings is calculated before subtracting the annual expenditures (as shown in the above table). Your function should return a list of fund sizes after each year of retirement, accounting for annual expenses and the growth of the retirement fund. Like problem 2, the length of the growthRates argument defines the number of years you plan to be retired.

# Note that if the retirement fund balance becomes negative, expenditures should continue to be subtracted, and the growth rate comes to represent the interest rate on the debt(i.e. the formulas in the above table still apply).

def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
      account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
      retirement.
    - return: a list of your retirement account value at the end of each year.
    """
    # TODO: Your code here.
    answer = [savings]
    for each in range(len(growthRates)):
        temp = answer[-1] * (1 + 0.01 * growthRates[each]) - expenses
        answer.append(temp)
#    del answer[0]
    return answer[-1]




def testPostRetirement():
    savings     = 100000
    growthRates = [10, 5, 0, 5, 1]
    expenses    = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord
    # Output should have values close to:
    # [80000.000000000015, 54000.000000000015, 24000.000000000015,
    # -4799.9999999999854, -34847.999999999985]

    # TODO: Add more test cases here.
    savings     = 367000
    growthRates = [10, 5, 0, 5, 1,5,6,7,8,9,1,2,3,4,5,6,12,13,14]
    expenses    = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord

    savings     = 900000
    growthRates = [10, 5, 0,10, 5, 0, 5, 1]
    expenses    = 60000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord

    savings     = 1500000
    growthRates = [10, 5, 0, 5, 1,10, 5, 0, 5, 1,6,7,8,4,3,1,8,9,0,21, 5, 0, 5, 1,6,7,8,4,3,1,8,9,0,12]
    expenses    = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord

    savings     = 1000000
    growthRates = [10, 5, 0, 5, 1,6,7,8,4,3,1,8,9,0,12]
    expenses    = 18000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord
    
    
# testPostRetirement() #Just for testing    

#
# Problem 4
#
# Start time: 2011-02-06 6:02 PM
# End time: 2011-02-06 6:42 PM
#
# Total time: minutes.


# Write a function, called findMaxExpenses, which takes five arguments: a salary(salary), a percentage of your salary to save (save), a list of annual growth percentages on investments while you are still working (preRetireGrowthRates), a list of annual growth percentages on investments while you are retired (postRetireGrowthRates), and a value for epsilon (epsilon). As with problems 2 and 3, the lengths of preRetireGrowthRates and postRetireGrowthRates determine the number of years you plan to be working and retired, respectively.

# Use the idea of binary search to find a value for the amount of expenses you can withdraw each year from your retirement fund, such that at the end of your retirement,the absolute value of the amount remaining in your retirement fund is less than epsilon(note that you can overdraw by a small amount). 

# Start with a range of possible values for your annual expenses between 0 and your savings at the start of your retirement (HINT #1: this can be determined by utilizing your solution to problem 2). Your function should print out the current estimate for the amount of expenses on each iteration through the binary search (HINT #2: your binary search should make use of your solution to problem 3), and should return the estimate for the amount of expenses to withdraw. (HINT #3: the answer should lie between zero and the initial value of the savings + epsilon.)

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,
                    epsilon):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments
      while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments
      while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in
      the investment fund at the end of retirement.
    """
    # TODO: Your code here.

    # Start with a range of possible values for your annual expenses between 0 and your savings at the start of your retirement (HINT #1: this can be determined by utilizing your solution to problem 2).
    low = 0
    
    ##  Set the high guess to value of the nest egg at moment of retirement or 1, which ever is higher.
    high = max(nestEggVariable(salary, save, preRetireGrowthRates)[-1],1)
    
    balanceAtRetirement = nestEggVariable(salary, save, preRetireGrowthRates)[-1]

    ##  Bisect the range between high & low and initialize the guess to this value.
    guess = (low + high) / 2
    
    ctr = 1
    
    ##  Set the remaining balance to the balance at the end of retirement (death?).
    remainingBalance = postRetirement(balanceAtRetirement, postRetireGrowthRates, guess)
    
    while abs(remainingBalance) > epsilon and ctr <= 100:
        #print 'low:', low, 'high:', high, 'guess:', guess, 'remainingBalance:',remainingBalance
        #print 'guess - remainingBalance', guess - remainingBalance
        if remainingBalance < 0:
            high = guess
        else:
            low = guess
        ctr += 1
        guess = (low + high)/2
        remainingBalance = postRetirement(balanceAtRetirement, postRetireGrowthRates, guess)
    assert ctr <= 100, 'Iteration count exceeded'
    return guess
    
def testFindMaxExpenses():
    salary                = 10000
    save                  = 10
    preRetireGrowthRates  = [3, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0, 5, 1]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses
    # Output should have a value close to:
    # 1229.95548986

    # TODO: Add more test cases here.

    salary                = 80000
    save                  = 10
    preRetireGrowthRates  = [3, 4, 5, 0, 3,6,7,8,5,4,7,4,8,9,11,21,11,2,5]
    postRetireGrowthRates = [3, 4, 5, 0, 3,6,7,8,5,4,7,4,8,2,5,10, 5, 0, 5, 1]
    epsilon               = 1000
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses
    
    salary                = 100000
    save                  = 15
    preRetireGrowthRates  = [3, 4, 5, 0, 3,6,7,8,5,4,7,4,8,9,11,21,11,2,5,3, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0,3, 4, 5, 0, 3,6,7,8,5,4,7,4,8,9,11,21,11,2,5, 5, 1]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses
    
    salary                = 1000
    save                  = 90
    preRetireGrowthRates  = [3, 4, 5, 0, 3,6,7,8,5,4,7,4,8,9,11,21,11,2,53, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0, 5, 1,3, 4, 5, 0, 3,6,7,8,5,4,7,4,8,9,11,21,11,2,5]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses

testFindMaxExpenses() # just to test
ochikobore (Self-grade: Outstanding)
Submitted 1 year ago | Permalink | Time spent: 12 hours
# Problem Set 4
# Name: Andrew
# Collaborators: CuriousReef
# Time: 12 hours

#
# Problem 1
#

def nestEggFixed(salary, save, growthRate, years):

    yearlyAcct = []

    for i in range(years):
        if not yearlyAcct: #if empty do this
            yearlyAcct.append(salary * save * 0.01)
        else:
            yearlyAcct.append(yearlyAcct[i-1] * (1 + 0.01 * growthRate) + salary * save * 0.01)

    return yearlyAcct

def testNestEggFixed():
    salary     = 10000
    save       = 10
    growthRate = 15
    years      = 5
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2150.0, 3472.5, 4993.375, 6742.3812499999995]

    # TODO: Add more test cases here.

#
# Problem 2
#

def nestEggVariable(salary, save, growthRates):

    yearlyAcct = []
    
    for growthRate in growthRates:
        if not yearlyAcct:
            yearlyAcct.append(salary * save * 0.01)
        else:
            yearlyAcct.append(yearlyAcct[-1] * (1 + 0.01 * growthRate) + salary * save * 0.01)

    return yearlyAcct

def testNestEggVariable():
    salary      = 10000
    save        = 10
    growthRates = [3, 4, 5, 0, 3]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002]

    # TODO: Add more test cases here.

#
# Problem 3
#
def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
      account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
      retirement.
    - return: a list of your retirement account value at the end of each year.
    """
    # TODO: Your code here.
    yearlyAcct = []

    if len(growthRates) < 1:
        return []

    yearlyAcct = [savings * (1 + 0.01 * growthRates[0]) - expenses]
    for growthRate in growthRates[1:]:
        yearlyAcct.append(yearlyAcct[-1] * (1 + 0.01 * growthRate) - expenses)
    
    return yearlyAcct

def testPostRetirement():
    savings     = 100000
    growthRates = [10, 5, 0, 5, 1]
    expenses    = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord
    # Output should have values close to:
    # [80000.000000000015, 54000.000000000015, 24000.000000000015,
    # -4799.9999999999854, -34847.999999999985]

    # TODO: Add more test cases here.

#
# Problem 4
#

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,
                    epsilon):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments
      while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments
      while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in
      the investment fund at the end of retirement.
    """
    # TODO: Your code here.

    savings = nestEggVariable(salary, save, preRetireGrowthRates)[-1]

    minimum = 0
    maximum = savings
    expenses = (minimum + maximum)*0.5

    while not abs(postRetirement(savings, postRetireGrowthRates, expenses)[-1]) < epsilon:

        if postRetirement(savings, postRetireGrowthRates, expenses)[-1] > 0:
            minimum = expenses
            expenses = (minimum + maximum)*0.5

        elif postRetirement(savings, postRetireGrowthRates, expenses)[-1] < 0:
            maximum = expenses
            expenses = (minimum + maximum)*0.5

    return expenses
        

def testFindMaxExpenses():
    salary                = 10000
    save                  = 10
    preRetireGrowthRates  = [3, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0, 5, 1]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses
    # Output should have a value close to:
    # 1229.95548986

    # TODO: Add more test cases here.

def main():
    testFindMaxExpenses()

if __name__ == "__main__":
    main()
tuckertuck (Self-grade: Outstanding)
Submitted 1 year ago | Permalink | Time spent: 2 hours

First project in a while where I understood everything the entire time, haha

# Problem Set 4
# Name: tuckertuck
# Collaborators: None 
# Time: 2:00

#
# Problem 1
#

def nestEggFixed(salary, save, growthRate, years):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an
      integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at
      the end of each year.
    """
    savings = []
    for n in range(0,years):
        if n == 0:
            fund = salary * save * 0.01
            savings.append(fund)
        else:
            fund = savings[-1] * (1 + 0.01 * growthRate) + salary * save * 0.01
            savings.append(fund)

    return savings
    

def testNestEggFixed():
    salary     = 10000
    save       = 10
    growthRate = 15
    years      = 5
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2150.0, 3472.5, 4993.375, 6742.3812499999995]

    salary     = 10000
    save       = 10
    growthRate = 15
    years      = 1
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord

#
# Problem 2
#

def nestEggVariable(salary, save, growthRates):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
      account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """
    account = []
    for n in range(0,len(growthRates)):
        if n == 0:
            fund = salary * save * 0.01
            account.append(fund)
        else:
            fund = account[n-1] * (1 + 0.01 * growthRates[n]) + salary * save * 0.01
            account.append(fund)

    return account


def testNestEggVariable():
    salary      = 10000
    save        = 10
    growthRates = [3, 4, 5, 0, 3]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002]

    # TODO: Add more test cases here.

#
# Problem 3
#

def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
      account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
      retirement.
    - return: a list of your retirement account value at the end of each year.
    """
    balance = []
    for n in range(0,len(growthRates)):
        if n == 0:
            fund = savings * (1 + 0.01 * growthRates[n]) - expenses
            balance.append(fund)
        else:
            fund = balance[n-1] * (1 + 0.01 * growthRates[n]) - expenses
            balance.append(fund)

    return balance

def testPostRetirement():
    savings     = 100000
    growthRates = [10, 5, 0, 5, 1]
    expenses    = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord
    # Output should have values close to:
    # [80000.000000000015, 54000.000000000015, 24000.000000000015,
    # -4799.9999999999854, -34847.999999999985]

    # TODO: Add more test cases here.

#
# Problem 4
#

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,
                    epsilon):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments
      while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments
      while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in
      the investment fund at the end of retirement.
    """
    
    minExpense = 0
    retirementFund = nestEggVariable(salary, save, preRetireGrowthRates)[-1]
    maxExpense = retirementFund
    expensesGuess = (minExpense + maxExpense)/2.0
    expensesTest = postRetirement(retirementFund, postRetireGrowthRates, expensesGuess)[-1]

    while abs(expensesTest) > epsilon:
        if expensesTest < epsilon:
            maxExpense = expensesGuess
        else:
            minExpense = expensesGuess
        expensesGuess = (minExpense + maxExpense)/2.0
        expensesTest = postRetirement(retirementFund, postRetireGrowthRates, expensesGuess)[-1]
    return expensesGuess


def testFindMaxExpenses():
    salary                = 10000
    save                  = 10
    preRetireGrowthRates  = [3, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0, 5, 1]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses
    # Output should have a value close to:
    # 1229.95548986

    # TODO: Add more test cases here.
Gpyti (Self-grade: Outstanding)
Submitted 1 year ago | Permalink | Time spent: 2 days
    F=[]
    b = salary*save*0.01
    F.append(b)
    for a in range (1,years):
       #print growthRates[a]
        c = b * (1 + 0.01 * preRetireGrowthRates[a]) + salary * save * 0.01
        F.append(c)
        b=c
    return F

#Problem 3
def testPostRetirement(savings,postRetireGrowthRates,expenses):
    years=len(postRetireGrowthRates)
    f=[]
    b=savings * (1+0.01 * postRetireGrowthRates[0]) - expenses
    f.append(b)
    for a in range(1,years):
        c = b * (1+0.01 * postRetireGrowthRates[a]) - expenses
        f.append(c)
        b=c
    return f


#savingsRecord = 
#print savingsRecord

#Problem 4

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates, epsilon):
    low=0
    high = testNestEggVariable(save,salary,preRetireGrowthRates)[-1]
    ctr=0
    savings=high
    guess=(low+high)/2.0
    lowest=testPostRetirement(savings,postRetireGrowthRates,guess)[-1]
    while abs(lowest) > epsilon and ctr <= 100:                             
            low = guess
        else:
            high = guess                                                   
        guess = (low + high) / 2.0                                          
        lowest = testPostRetirement(savings, postRetireGrowthRates, guess)[-1]   
    return guess


    
##    pre = len(preRetireGrowthRates)
##    post = len(postRetireGrowthRates)
##    
##    F = totalSavings[-1]
##    Guess = (F + epsilon) / 2
##    totalsavingsafter = testPostRetirement(F,postRetireGrowthRates,Guess)
##    while Guess*10>totalSavings:
##        ctr=ctr+1
##        F = (F + epsilon) / 2
##        totalsavingsafter = testPostRetirement(F,postRetireGrowthRates,F)
##    print F,Guess
##

mjcuva (Self-grade: Outstanding)
Submitted 1 year ago | Permalink | Time spent: 2 hours

pset 4

## Name:  Marc
## Time: ~2 Hours

#==========Problem 1==========

def nestEggFixed(salary, save, growthRate, years):
    """
    - salary: the amount of money you amke each year.
    - save: the percent of your salary to save in the investment account each year( an integer between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at the end of each year.
    """
    
    f = []                                                                  #Create a list to hold all of the values
    f.append(salary * save * 0.01)                                          #Add the amount earned for the first year
    for i in range(1,years):                                                #Loop that counts through the rest of the years
        
        f.append(f[i - 1] * (1+0.01*growthRate) + salary * save * 0.01)     #Add the result of the formula that calculates
                                                                            #the amount at the end of the year
    return f

def testNestEggFixed():
    """
    Tests the function NestEggFixed
    """

    salary = 10000
    save = 10
    growthRate = 15
    years = 5
    savingRecord = nestEggFixed(salary,save,growthRate,years)
    print savingRecord

#==========Problem 2==========

def nestEggVariable(salary, save, growthRate):
    """
    - salary: thee amount of money you make each year.
    - Save: the percent of your salary to save in teh investment account each year9 an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """

    f = []                                                                  #Create a list to hold all of the values
    f.append(salary * save * 0.01)                                          #Add the amount earned for the first year

    for i in range(1,len(growthRate)):                                      #Loop that counts through the rest of the years, with 
                                                                            #the length of the list growthRate as the amount of years
        f.append(f[i-1] * (1+0.01*growthRate[i]) + salary * save * 0.01)    #Add the result of the the formula that calculates
                                                                            #the amount at the end of the year
    return f

def testNestEggVariable():
    """
    Tests the function NestEggVariable.
    """
    
    salary = 10000
    save = 10
    growthRates = [3,4,5,0,3]
    savingRecord = nestEggVariable(salary, save, growthRates)
    print savingRecord

#==========Problem 3==========

def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
    - expenses: the amount of money you plan to spend each year during retirement.
    - return: a list of your retirement account value at the end of each year.
    """

    f = []                                                          #Create a list to hold all of the values
    f.append(savings*(1+0.01*growthRates[0]) - expenses)            #Add the amount earned for the first year, minus your expenses

    for i in range(1,len(growthRates)):                             #Loop that counts through the rest of the years, with the length of 
                                                                    #the list growthRates as the amount of years
        f.append(f[i-1]*(1 + 0.01 * growthRates[i]) - expenses)     #Add the result of the formula that calculates the amount
                                                                    #at the end of the year, minus your expeses
    return f

def testPostRetirement():
    """
    Tests the function Postretirement
    """
    
    savings = 100000
    growthRates = [10,5,0,5,1]
    expenses = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord

#==========Problem 4==========

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates, epsilon):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in the investment fund at the end of retirement.
    """

    low = 0                                                                 #Set the lower bound of the Binary Search to 0
    high = nestEggVariable(salary, save, preRetireGrowthRates)[-1]          #Set the upper bound of the Binary Search to the amount of money 
                                                                            #earned before retirment
    savings = high                                                          
    guess = (low + high)/2.0                                                #Make your guess halfway between the upper and lower bounds
    ctr = 1                                                                 #Set a control to count the number of iterations
    
    dead = postRetirement(savings, postRetireGrowthRates,guess)[-1]         #Determine the amount of money you will have left when you die
                                                                            #with the guess as your expenses
    
    while abs(dead) > epsilon and ctr <= 100:                               #Check if the amount left is less than epsilon
        if dead > epsilon:                                                  #If you didn't spend enough money, change the lower bound to the guess
            low = guess
        else:
            high = guess                                                    #If you spent to much money, change the upper bound to the guess
        guess = (low + high) / 2.0                                          #Determine a new guess
        dead = postRetirement(savings, postRetireGrowthRates, guess)[-1]    #Calculate the amount of money you have left with the new guess as the expense
    return guess

def testFindMaxExpenses():
    """
    Tests the function FindMaxExpenses
    """
    
    salary = 10000
    save = 10
    preRetireGrowthRates = [3,4,5,0,3]
    postRetireGrowthRates = [10,5,0,5,1]
    epsilon = .01
    expenses = findMaxExpenses(salary,save,preRetireGrowthRates,postRetireGrowthRates,epsilon)

    print expenses
    
xwb1989 (Self-grade: Outstanding)
Submitted 2 years ago | Permalink | Time spent: 5 hours
# Problem Set 4
# Name: 
# Collaborators: 
# Time: 

#
# Problem 1


def nestEggFixed(salary, save, growthRate, years):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an
      integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at
      the end of each year.
    """
    # TODO: Your code here.
    RA = [salary*save*0.01]
    ctr = 1
    while ctr<years:
        RA.append(salary*save*0.01 +(1+growthRate*0.01)*RA[len(RA)-1])
        ctr += 1
    return RA
##savings = 0
##RA = []
##def nestEggFixedR(savings,RA,salary, save, growthRate, years):
##    
##    if years == 0:
##        return RA
##    else:
##        savings = salary*save*0.01 + savings*(1+growthRate*0.01)
##        RA.append(savings)
##        return nestEggFixedR(savings,RA,salary, save, growthRate, years-1)
def testNestEggFixed():
    salary     = 10000
    save       = 10
    growthRate = 15
    years      = 5
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print(savingsRecord)

def testNestEggFixedR():
    salary     = 10000
    save       = 10
    growthRate = 15
    years      = 5
    savingsRecord = nestEggFixedR(savings,RA,salary, save, growthRate, years)
    print(savingsRecord)
    
    # Output should have values close to:
    # [1000.0, 2150.0, 3472.5, 4993.375, 6742.3812499999995]

    # TODO: Add more test cases here.
testNestEggFixedR()

#Problem 2


def nestEggVariable(salary, save, growthRates):
    # TODO: Your code here.
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
      account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """
    RA = []
    ctr = 0
    savings = 0
    while ctr<len(growthRates):
        ctr += 1
        savings = savings*(1+growthRates[ctr-1]*0.01)+salary*save*0.01
        RA.append(savings)
    return RA
    

def testNestEggVariable():
    salary      = 10000
    save        = 10
    growthRates = [3, 4, 5, 0, 3]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print (savingsRecord)
    # Output should have values close to:
    # [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002]

    # TODO: Add more test cases here.
testNestEggVariable()
#####
#Problem 3


def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
      account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
      retirement.
    - return: a list of your retirement account value at the end of each year.
    """
    # TODO: Your code here.
    RA = []
    ctr = 0
    while ctr<len(growthRates):
        savings = savings*(1+growthRates[ctr]*0.01) - expenses
        RA.append(savings)
        ctr += 1
    return RA
def testPostRetirement():
    savings     = 100000
    growthRates = [10, 5, 0, 5, 1]
    expenses    = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print (savingsRecord)
    # Output should have values close to:
    # [80000.000000000015, 54000.000000000015, 24000.000000000015,
    # -4799.9999999999854, -34847.999999999985]

    # TODO: Add more test cases here.
testPostRetirement()


# Problem 4
#

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,
                    epsilon):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments
      while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments
      while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in
      the investment fund at the end of retirement.
    """
    # TODO: Your code here.
    def Bimethod(savings,epsilon, postRetireGrowthRates):
        assert savings>0
        assert epsilon>0
        ctr = 1
        low = 0
        high = max(1,savings)
        expenses = (low+high)/2.0
        print(expenses)
        lastleft = postRetirement(savings, postRetireGrowthRates, expenses)[len(postRetireGrowthRates)-1]
        print(lastleft)
        while abs(lastleft) > epsilon:
            if lastleft > 0:
                low = expenses
            else:
                high = expenses
            expenses = (high + low)/2
##            print(expenses)
            lastleft = postRetirement(savings, postRetireGrowthRates, expenses)[len(postRetireGrowthRates)-1]
        return expenses

    savings = nestEggVariable(salary, save, preRetireGrowthRates)[len(preRetireGrowthRates)-1]
    return Bimethod(savings, epsilon, postRetireGrowthRates)
    
def testFindMaxExpenses():
    salary                = 20000
    save                  = 10
    preRetireGrowthRates  = [3, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0, 5, 1]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print (expenses)
    
testFindMaxExpenses()
    # Output should have a value close to:
    # 1229.95548986

    # TODO: Add more test cases here.
fredgust (Self-grade: Pretty good)
Submitted 2 years ago | Permalink | Time spent: 1 hour
# Problem Set 4
# Name: Fredrik Gustafsson
# Python Version: 3.2 
# Time: 01:00

#
# Problem 1
#

def nestEggFixed(salary, save, growthRate, years):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an
      integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at
      the end of each year.
    """
    f = []
    f.append(salary*save*0.01)
    for x in range(years-1):
        f.append(f[x]*(1+0.01*growthRate)+salary*save*0.01)
    return f
    
    
def testNestEggFixed():
    salary     = 10000
    save       = 10
    growthRate = 15
    years      = 5
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print (savingsRecord)
    # Output should have values close to:
    # [1000.0, 2150.0, 3472.5, 4993.375, 6742.3812499999995]


#
# Problem 2
#

def nestEggVariable(salary, save, growthRates):
    # TODO: Your code here.
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
      account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """
    f = []
    f.append(salary*save*0.01)
    for x in range(len(growthRates)-1):
        f.append(f[x]*(1+0.01*growthRates[x+1])+salary*save*0.01)
    return f

def testNestEggVariable():
    salary      = 10000
    save        = 10
    growthRates = [3, 4, 5, 0, 3]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print (savingsRecord)
    # Output should have values close to:
    # [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002]

   
#
# Problem 3
#

def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
      account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
      retirement.
    - return: a list of your retirement account value at the end of each year.
    """
    f = []
    f.append(savings*(1+0.01*growthRates[0])-expenses)
    for x in range(len(growthRates)-1):
        f.append(f[x]*(1+0.01*growthRates[x+1])-expenses)
    return f

def testPostRetirement():
    savings     = 100000
    growthRates = [10, 5, 0, 5, 1]
    expenses    = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print (savingsRecord)
    # Output should have values close to:
    # [80000.000000000015, 54000.000000000015, 24000.000000000015,
    # -4799.9999999999854, -34847.999999999985]


#
# Problem 4
#

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,
                    epsilon):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments
      while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments
      while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in
      the investment fund at the end of retirement.
    """
    f = nestEggVariable(salary, save, preRetireGrowthRates
                        )[len(preRetireGrowthRates)-1]
    low = f / len(postRetireGrowthRates)
    high = f
    guess = (low  + high) / 2
    ctr = 0
    while abs(postRetirement(f, postRetireGrowthRates, guess)
              [len(postRetireGrowthRates)-1]) > epsilon and ctr <=100:
        if (postRetirement(f, postRetireGrowthRates, guess)
            [len(postRetireGrowthRates)-1]) > epsilon:
            low = guess
        else: 
            high = guess
        guess = (low + high) / 2
        ctr += 1
    assert ctr <=100, 'Iteration count exceeded'
    return guess
    
def testFindMaxExpenses():
    salary                = 10000
    save                  = 10
    preRetireGrowthRates  = [3, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0, 5, 1]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print (expenses)
    # Output should have a value close to:
    # 1229.95548986
mercutio22 (Self-grade: Pretty good)
Submitted 2 years ago | Permalink | Time spent: 5 days
#!/usr/bin/env python
#encoding=utf-8

# Problem Set 4
# Name: Hugo A. M. Torres
# Collaborators: friendless ;-(
# Time: Sun Oct 24 00:50:11 BRST 2010

#
# Problem 1
#

def nestEggFixed(salary, save, growthRate, years):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an
      integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at
      the end of each year.
    """
 
    GreeniesYearZero = salary * save * 0.01  
    TotalGreenies=[GreeniesYearZero]#Essa lista irá guardar os valores do meu fundo de aposentadoria ao final de cada ano
    span = range(years)  
    for year in span[1:]:
        GreeniesNow = TotalGreenies[year-1]* (1 + 0.01 * growthRate) + salary * save * 0.01 
        TotalGreenies.append(GreeniesNow)
    return TotalGreenies


def testNestEggFixed():
    salary     = 10000
    save       = 10
    growthRate = 15
    years      = 5
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2150.0, 3472.5, 4993.375, 6742.3812499999995]

    # TODO: Add more test cases here.

#testNestEggFixed()

#
# Problem 2
#

def nestEggVariable(salary, save, growthRates):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
      account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """
    GreeniesYearZero = salary * save * 0.01  
    TotalGreenies=[GreeniesYearZero]#Essa lista irá guardar os valores do meu fundo de aposentadoria ao final de cada ano
    span = range(len(growthRates))  
    for year in span[1:]:
        GreeniesNow = TotalGreenies[year-1]* (1 + 0.01 * growthRates[year]) + salary * save * 0.01 
        TotalGreenies.append(GreeniesNow)
    return TotalGreenies

def testNestEggVariable():
    salary      = 10000
    save        = 10
    growthRates = [3, 4, 5, 0, 3]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002]

    # TODO: Add more test cases here.
#testNestEggVariable()
#
# Problem 3
#

def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
      account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
      retirement.
    - return: a list of your retirement account value at the end of each year.
    """
    # TODO: Your code here.
    GreeniesYearZero = savings * (1 + 0.01 * growthRates[0]) - expenses 
    TotalGreenies=[GreeniesYearZero]#Essa lista irá guardar os valores do meu fundo de aposentadoria ao final de cada ano
    span = range(len(growthRates))  
    for year in span[1:]:
        GreeniesNow = TotalGreenies[year-1]* (1 + 0.01 * growthRates[year]) -expenses 
        TotalGreenies.append(GreeniesNow)
    return TotalGreenies


def testPostRetirement():
    savings     = 100000
    growthRates = [10, 5, 0, 5, 1]
    expenses    = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord
    # Output should have values close to:
    # [80000.000000000015, 54000.000000000015, 24000.000000000015,
    # -4799.9999999999854, -34847.999999999985]

    # TODO: Add more test cases here.

#
# Problem 4
#

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,
                    epsilon):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments
      while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments
      while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in
      the investment fund at the end of retirement.
    """
    assert epsilon > 0

    savings = nestEggVariable(salary,save,preRetireGrowthRates)# gets the list of retirement fund value per year during the working epoch
    
    #============ This block guesses the amount of expenses per year and calculates Retirement fund values per year while retired such that nothing is left by time of death
    high = savings[-1] + epsilon
    low = 0
    ctr = 1 #keeps track of the number of iterations the binary search takes untill finding the answer
    expending = [savings[-1]]
    print 'first attemp:', expending
    while abs(expending[-1]) > epsilon and ctr < 1000:
        guess = (high + low) / 2
        expending = postRetirement(savings[-1], postRetireGrowthRates, guess)# gets the list of retirement fund value per year during the retirement epoch
        if expending[-1] > 0:
            low = guess
        else:
            high = guess
        guess = (high + low) / 2
        ctr += 1
        print 'n-th attempt', expending
    assert ctr <= 1000, 'Iteration count exceeded'
    print 'Bi method. Num. iterations:', ctr, 'Estimate:', guess
    return expending[-1]

def testFindMaxExpenses():
    salary                = 10000
    save                  = 10
    preRetireGrowthRates  = [3, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0, 5, 1]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses
testFindMaxExpenses()
    # Output should have a value close to:
    # 1229.95548986

    # TODO: Add more test cases here.
dacorest (Self-grade: Outstanding)
Submitted 2 years ago | Permalink | Time spent: 1 minute
#Name : Waz 
#Problem set 4

___________________Problem 1________________________

#plan
#make sure arguments are of right format
#declare variable for list & year counter
#create loop for counter

def nestEggFixed(salary, save, growthRate, years):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an
      integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at
      the end of each year.
    """
    assert save >= 0 and save <=100, "Save should be between 0-100"
    assert growthRate >= 0 and growthRate <=100, "growthRate should be between 0-100"
    
    thelist = ['tobefilled'] #the list to be returned
    counter = 1 # counter for loop
    if years == 0:
        thelist[0]='Your retirement account is empty'
    elif years == 1:
        thelist[0]=salary*save*0.01
    else:
        thelist[0]=salary*save*0.01
        while counter<years:
            thelist.append(thelist[counter-1]*(1+0.01*growthRate)+salary*save*0.01)
            counter = counter + 1
    return thelist

    
    

def testNestEggFixed():
    salary     = 10000
    save       = 10
    growthRate = 15
    years      = 5
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2150.0, 3472.5, 4993.375, 6742.3812499999995]
    
def testNestEggFixed2():
    salary     = 24000
    save       = 10
    growthRate = 7
    years      = 5
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord
    # Output should have values close to:
    # [2400.0, 4968.0, 7715.76, 10655.863200000002, 13801.773624000003]

#_____________________ Problem 2__________________
#
def isbetween0to100(alist): #will be used for assertion
    """Test if elements of a list is between 0 and 100"""
    for i in alist:
        if i < 0 or i > 100:
            return "False"
        

def nestEggVariable(salary, save, growthRates):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
      account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """
    assert save >= 0 and save <=100, "Save should be between 0-100"
    assert isbetween0to100(growthRates)!="False", "growthRates should be between 0-100"

    thelist = ['tobefilled'] #the list to be returned
    counter = 1 # counter for loop
    if len(growthRates) == 0:
        thelist[0]='Your retirement account is empty'
    elif len(growthRates) == 1:
        thelist[0]=salary*save*0.01
    else:
        thelist[0]=salary*save*0.01
        while counter<len(growthRates):
            thelist.append(thelist[counter-1]*(1+0.01*growthRates[counter])+salary*save*0.01)
            counter = counter + 1
    return thelist



def testNestEggVariable():
    salary      = 10000
    save        = 10
    growthRates = [3, 4, 5, 0, 3]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002]

def testNestEggVariable2():
    salary      = 60000
    save        = 15
    growthRates = [9,2,7,6,5]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord
    # Output should have values close to:
    # [9000.0, 18180.0, 28452.600000000002, 39159.75600000001, 50117.74380000001]


# _____________________________Problem 3_______________
#
def isbetween0to100(alist): #will be used for assertion
    """Test if elements of a list is between 0 and 100"""
    for i in alist:
        if i < 0 or i > 100:
            return "False"
   
def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
      account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
      retirement.
    - return: a list of your retirement account value at the end of each year.
    """
    assert isbetween0to100(growthRates)!="False", "growthRates should be between 0-100"
        ### Why only 0-100? I'd think at the very least that negative growth would be possible, e.g. years 2007/8
    thelist = ['tobefilled'] #the list to be returned
    counter = 1 # counter for loop
    if len(growthRates) == 0:
        thelist[0]='Your retirement account is empty'
    elif len(growthRates) == 1:
        thelist[0]=savings * (1 + 0.01 * growthRates[0])- expenses 
    else:
        thelist[0]=savings * (1 + 0.01 * growthRates[0])- expenses 
        while counter<len(growthRates):
            thelist.append(thelist[counter-1]*(1+0.01*growthRates[counter])-expenses)
            counter = counter + 1
    return thelist
    
def testPostRetirement():
    savings     = 100000
    growthRates = [10, 5, 0, 5, 1]
    expenses    = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord
    # Output should have values close to:
    # [80000.000000000015, 54000.000000000015, 24000.000000000015,
    # -4799.9999999999854, -34847.999999999985]
def testPostRetirement2():
    savings     = 50000
    growthRates = [3,9,4]
    expenses    = 2000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord
    # Output should have values close to:
    # [49500.0, 51955.000000000007, 52033.200000000012]
# _______________________Problem 4__________________
#
def nestEggVariable(salary, save, growthRates):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
      account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """
    assert save >= 0 and save <=100, "Save should be between 0-100"
    assert isbetween0to100(growthRates)!="False", "growthRates should be between 0-100"
    thelist = ['tobefilled'] #the list to be returned
    counter = 1 # counter for loop
    if len(growthRates) == 0:
        thelist[0]='Your retirement account is empty'
    elif len(growthRates) == 1:
        thelist[0]=salary*save*0.01
    else:
        thelist[0]=salary*save*0.01
        while counter<len(growthRates):
            thelist.append(thelist[counter-1]*(1+0.01*growthRates[counter])+salary*save*0.01)
            counter = counter + 1
    return thelist
def isbetween0to100(alist): #will be used for assertion
    """Test if elements of a list is between 0 and 100"""
    for i in alist:
        if i < 0 or i > 100:
            return "False"
   
def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
      account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
      retirement.
    - return: a list of your retirement account value at the end of each year.
    """
    assert isbetween0to100(growthRates)!="False", "growthRates should be between 0-100"
   
    thelist = ['tobefilled'] #the list to be returned
    counter = 1 # counter for loop
    if len(growthRates) == 0:
        thelist[0]='Your retirement account is empty'
    elif len(growthRates) == 1:
        thelist[0]=savings * (1 + 0.01 * growthRates[0])- expenses 
    else:
        thelist[0]=savings * (1 + 0.01 * growthRates[0])- expenses 
        while counter<len(growthRates):
            thelist.append(thelist[counter-1]*(1+0.01*growthRates[counter])-expenses)
            counter = counter + 1
    return thelist

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,
                    epsilon):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments
      while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments
      while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in
      the investment fund at the end of retirement.
    """
    thesavingsbyyear =nestEggVariable(salary,save,preRetireGrowthRates)
    thesavings=thesavingsbyyear[-1]
    #i m about to try to find the value for expenses in postRetirement where
    # postRetirement(thesavings+epsilon,postRetireGrowthRates,expenses)[len(postRetireGrowthRates)-1]=0
    exphigh=thesavings
    explow=0
    guess=(exphigh+explow)/2
    limitcounter =0 
    limit = 150 #i know its high ;-)
    
    while postRetirement(thesavings+epsilon,postRetireGrowthRates,guess)[len(postRetireGrowthRates)-1]!=0:
        while postRetirement(thesavings+epsilon,postRetireGrowthRates,guess)[len(postRetireGrowthRates)-1]>0:
            print 'You have to spend more than ',guess,' annually. \n'
            explow = guess
            guess=(exphigh+explow)/2
            limitcounter = limitcounter + 1
            if limitcounter > limit:
                return "You passed the iteration limit"
        while postRetirement(thesavings+epsilon,postRetireGrowthRates,guess)[len(postRetireGrowthRates)-1]<0:
            print 'You have to spend less than ',guess,' annually. \n'
            exphigh = guess
            guess=(exphigh+explow)/2
            limitcounter = limitcounter + 1
            if limitcounter > limit:
                return "You passed the iteration limit"
    return guess
    
    
    

def testFindMaxExpenses():
    salary                = 10000
    save                  = 10
    preRetireGrowthRates  = [3, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0, 5, 1]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses
    # Output should have a value close to:
    # 1229.95548986
def testFindMaxExpenses2():
    salary                = 60000
    save                  = 15
    preRetireGrowthRates  = [8,9,4,5,9,8,9,8,5,0,0,5]
    postRetireGrowthRates = [1,6,6,5,1,8,1]
    epsilon               = .001
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses
    # Output should have a value close to:
    # 23616.7691323
conwayblue (Self-grade: Pretty good)
Submitted 2 years ago | Permalink | Time spent: 1 day
# Problem Set 4
# Name: 
# Collaborators: 
# Time: 

#
# Problem 1--------------------------------------------------------------------------
#

def nestEggFixed(salary, save, growthRate, years):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an
      integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at
      the end of each year.
    """
    # TODO: Your code here.

    #return a list [total acct size, this year]

    counter = 0
    f = [salary*save*0.01]

    while counter + 1 < years:
        f.append(f[counter] * (1 + 0.01*growthRate) + f[0])
        counter += 1
    return f


def testNestEggFixed():
    salary     = 10000
    save       = 10
    growthRate = 15
    years      = 5
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2150.0, 3472.5, 4993.375, 6742.3812499999995]

    # TODO: Add more test cases here.

#
# Problem 2------------------------------------------------------------------------
#

def nestEggVariable(salary, save, growthRates):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
      account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """
    # TODO: Your code here.    
     
    counter = 0
    f = [salary*save*0.01]

    while counter + 1 < len(growthRates):
        f.append(f[counter] * (1 + 0.01 * growthRates[counter+1]) + f[0])
        counter += 1
    return f
    

def testNestEggVariable():
    salary      = 10000
    save        = 10
    growthRates = [3, 4, 5, 0, 3]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002]

    # TODO: Add more test cases here.

#
# Problem 3------------------------------------------------------------------------
#

def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
      account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
      retirement.
    - return: a list of your retirement account value at the end of each year.
    """
    # TODO: Your code here.

    counter = 0
    f = [savings * (1 + 0.01*growthRates[0]) - expenses]

    while counter + 1 < len(growthRates):
        f.append(f[counter] * (1 + 0.01 * growthRates[counter+1]) - expenses)
        counter += 1
    return f
        

def testPostRetirement():
    savings     = 100000
    growthRates = [10, 5, 0, 5, 1]
    expenses    = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord
    # Output should have values close to:
    # [80000.000000000015, 54000.000000000015, 24000.000000000015,
    # -4799.9999999999854, -34847.999999999985]

    # TODO: Add more test cases here.

#
# Problem 4----------------------------------------------------------------------
#

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,
                    epsilon):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments
      while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments
      while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in
      the investment fund at the end of retirement.
    """
    # TODO: Your code here.

    savings = nestEggVariable(salary,save,preRetireGrowthRates)[-1]
    lowGuess = 0
    highGuess = savings
    expenses = (lowGuess + highGuess) / 2.0
    dead = postRetirement(savings,postRetireGrowthRates,expenses)[-1]
    counter = 1

    while abs(dead) > epsilon and counter <= 100:
        if dead > epsilon:  #if money left, expenses were to low
            lowGuess = expenses
        else:
            highGuess = expenses
        expenses = (lowGuess + highGuess) / 2.0
        dead = postRetirement(savings,postRetireGrowthRates,expenses)[-1]
        counter += 1
    return expenses
        
        
    
def testFindMaxExpenses():
    
    salary                = 10000
    save                  = 10
    preRetireGrowthRates  = [3, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0, 5, 1]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses
    # Output should have a value close to:
    # 1229.95548986

    # TODO: Add more test cases here.
DvorakAJS (Self-grade: Pretty good)
Submitted 2 years ago | Permalink | Time spent: 2 hours

didn't add what wasn't really needed, if I can make it shorter somewhere please do tell me :)

thanks

def nestEggFixed(salary, save, growthRate, years):
    years_list=[]
    years_list.append((salary*save)/100.0)
    for year in range(1,years):
         years_list.append(years_list[year-1]*(1+(growthRate/100.0))+(salary*save)/100.0)
    return years_list

def nestEggVariable(salary, save, growthRates):
    years_to_work=len(growthRates)
    years_list=[]
    years_list.append((salary*save)/100.0)
    for year in range(1,years_to_work):
       	years_list.append(years_list[year-1]*(1+(growthRates[year]/100.0))+(salary*save)/100.0)
    return years_list

def postRetirement(savings, growthRates, expenses):
    years_to_get_money=len(growthRates)
    years_list=[]
    years_list.append(savings*(1+(growthRates[0]/100.0))-expenses)
    for year in range(1,years_to_get_money):
        years_list.append(years_list[year-1]*(1+(growthRates[year]/100.0))-expenses)

    return years_list



def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,epsilon):
    total_money_start_retirement=nestEggVariable(salary, save, preRetireGrowthRates)[-1]
    low_guess=0
    high_guess=total_money_start_retirement
    expenses=(low_guess+high_guess)/2.0
    end_money=postRetirement(total_money_start_retirement, postRetireGrowthRates, expenses)[-1]
    
    print "if expenses are: ",expenses,". leftovers are: ",end_money

    while abs(end_money) > epsilon:
        if end_money > epsilon :low_guess=expenses

        else: high_guess=expenses
        
        expenses=(low_guess+high_guess)/2.0
        end_money=postRetirement(total_money_start_retirement, postRetireGrowthRates, expenses)[-1]
        print "if expenses are: ",expenses,". leftovers are: ",end_money
rfh (Self-grade: Pretty good)
Submitted 2 years ago | Permalink
# Problem 1
#
# Write a function, called nestEggFixed, which takes four arguments: a
# salary, a percentage of your salary to save in an investment account,
# an annual growth percentage for the investment account, and a number
# of years to work. This function should return a list, whose values are
# the size of your retirement account at the end of each year, with the
# most recent year's value at the end of the list.

def nestEggFixed(salary, save, growthRate, years):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an
      integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at
      the end of each year.
    """

    yearlyAddAmount = salary * .01 * save

    savingsEachYear = (yearlyAddAmount,)

    for year in range(1, years):
        lastYearsBalance    = savingsEachYear[-1]
        thisYearsBalance    = lastYearsBalance * (1 + .01 * growthRate) + yearlyAddAmount
        savingsEachYear     = savingsEachYear + (thisYearsBalance,)

    return savingsEachYear

def testNestEggFixed():
    salary     = 10000
    save       = 10
    growthRate = 15
    years      = 5

    print "Testing nestEggFixed with salary: %d, save: %d, growthRate: %d, years: %d" % (salary, save, growthRate, years)
    savingsRecord = nestEggFixed(salary, save, growthRate, years)

    print "Should be", (1000.0, 2150.0, 3472.5, 4993.375, 6742.3812499999995)
    print "Is actually", savingsRecord

    # TODO: Add more test cases here.
    assert savingsRecord[0] < savingsRecord[1]
    assert savingsRecord[1] < savingsRecord[2]
    assert savingsRecord[2] < savingsRecord[3]
    assert savingsRecord[3] < savingsRecord[4]


#
# Problem 2
#
# Write a function, called nestEggVariable, which takes three arguments:
# a salary (salary), a percentage of your salary to save (save), and a
# list of annual growth percentages on investments (growthRates). The
# length of the last argument defines the number of years you plan to
# work; growthRates[0] is the growth rate of the first year,
# growthRates[1] is the growth rate of the second year, etc. (Note that
# because the retirement fund's initial value is 0, growthRates[0] is,
# in fact, irrelevant.) This function should return a list, whose values
# are the size of your retirement account at the end of each year.

def nestEggVariable(salary, save, growthRates):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
      account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """
    yearlyAddAmount = salary * .01 * save

    savingsEachYear = (yearlyAddAmount,)

    years = len(growthRates)

    for year in range(1, years):
        lastYearsBalance    = savingsEachYear[-1]
        thisYearsBalance    = lastYearsBalance * (1 + .01 * growthRates[year]) + yearlyAddAmount

        savingsEachYear = savingsEachYear + (thisYearsBalance,)

    return savingsEachYear
        

def testNestEggVariable():
    salary      = 10000
    save        = 10
    growthRates = [3, 4, 5, 0, 3]

    print "Testing nestEggVariable with salary: %d, save: %d, growthRates: " % (salary, save), growthRates
    savingsRecord = nestEggVariable(salary, save, growthRates)

    print "Should be", (1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002)
    print "Is actually", savingsRecord

    assert savingsRecord[0] < savingsRecord[1]
    assert savingsRecord[1] < savingsRecord[2]
    assert savingsRecord[2] < savingsRecord[3]
    assert savingsRecord[3] < savingsRecord[4]


#
# Problem 3
#
# Write a function, called postRetirement, which takes three arguments:
# an initial amount of money in your retirement fund (savings), a list
# of annual growth percentages on investments while you are retired
# (growthRates), and your annual expenses (expenses). Assume that the
# increase in the investment account savings is calculated before
# subtracting the annual expenditures (as shown in the above table).
# Your function should return a list of fund sizes after each year of
# retirement, accounting for annual expenses and the growth of the
# retirement fund. Like problem 2, the length of the growthRates
# argument defines the number of years you plan to be retired.
#
# Note that if the retirement fund balance becomes negative,
# expenditures should continue to be subtracted, and the growth rate
# comes to represent the interest rate on the debt (i.e. the formulas in
# the above table still apply).
# 

def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
      account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
      retirement.
    - return: a list of your retirement account value at the end of each year.
    """
    year1 = savings * (1 + 0.01 * growthRates[0]) - expenses
    savingsEachYear = (year1,)
    years = len(growthRates)

    for year in range(1, years):
        lastYearsBalance = savingsEachYear[-1]
        thisYearsBalance = lastYearsBalance * (1 + 0.01 * growthRates[year]) - expenses

        savingsEachYear = savingsEachYear + (thisYearsBalance,)

    return savingsEachYear


def testPostRetirement():
    savings     = 100000
    growthRates = [10, 5, 0, 5, 1]
    expenses    = 30000

    print "Testing postRetirement with savings: %d, expenses: %d, growthRates: " % (savings, expenses), growthRates
    savingsRecord = postRetirement(savings, growthRates, expenses)

    print "Should be", (80000.000000000015, 54000.000000000015, 24000.000000000015, -4799.9999999999854, -34847.999999999985)
    print "Is actually", savingsRecord
    
    assert savingsRecord[0] > savingsRecord[1]
    assert savingsRecord[1] > savingsRecord[2]
    assert savingsRecord[2] > savingsRecord[3]
    assert savingsRecord[3] > savingsRecord[4]


#
# Problem 4
#
# Write a function, called findMaxExpenses, which takes five arguments:
# a salary (salary), a percentage of your salary to save (save), a list
# of annual growth percentages on investments while you are still
# working (preRetireGrowthRates), a list of annual growth percentages on
# investments while you are retired (postRetireGrowthRates), and a value
# for epsilon (epsilon). As with problems 2 and 3, the lengths of
# preRetireGrowthRates and postRetireGrowthRates determine the number of
# years you plan to be working and retired, respectively.

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,
                    epsilon):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments
      while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments
      while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in
      the investment fund at the end of retirement.
    """
    yearsWorking = len(preRetireGrowthRates)
    yearsRetired = len(postRetireGrowthRates)

    savings = nestEggVariable(salary, save, preRetireGrowthRates)[-1]

    count = 0

    low = 0
    high = savings
    guess = (high - low) / 2
    finalBalance = epsilon + 1

    while abs(finalBalance) >= epsilon:
        print "Current guess for expenses: %0.2f" % guess
        finalBalance = postRetirement(savings, postRetireGrowthRates, guess)[-1]
        print "Final balance for this guess is: %0.8f" % finalBalance

        if (finalBalance < epsilon):
            high = guess
        else:
            low = guess
            
        guess = (high - low) / 2 + low

    assert count < 100, 'Maximum number of iterations exceeded'

    return guess

def testFindMaxExpenses():
    salary                = 10000
    save                  = 10
    preRetireGrowthRates  = [3, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0, 5, 1]
    epsilon               = .01

    print "Testing findMaxExpenses with salary: %d, save: %d, epsilon: %0.2f, pre & post retirement growth rates respectively" % (salary, save, epsilon), preRetireGrowthRates, postRetireGrowthRates
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)

    print "Should be close to 1229.95548986"
    print "Is actually %0.8f" % expenses

testNestEggFixed()
print
testNestEggVariable()
print
testPostRetirement()
print
testFindMaxExpenses()

Comments:

fredgust
2 years ago

Hi, I noticed that the count variable don't do anything in your solution to problem 4. You need to increment the variable inside the while loop and then move the assert statement inside the loop.

 while abs(finalBalance) >= epsilon:
        print "Current guess for expenses: %0.2f" % guess
        finalBalance = postRetirement(savings, postRetireGrowthRates, guess)[-1]
        print "Final balance for this guess is: %0.8f" % finalBalance

        if (finalBalance < epsilon):
            high = guess
        else:
            low = guess
            
        guess = (high - low) / 2 + low
        count += 1
        assert count < 100, 'Maximum number of iterations exceeded'
rfh
2 years ago

You are right, thanks for the correction.

Sign up or log in to comment

lf7 (Self-grade: Outstanding)
Submitted 2 years ago | Permalink
# Problem Set 4
# Name: lf7
# Collaborators: Santa Claus, Rudolf and Sarah Palin
# Time: Some even finite sum of two prime numbers, in units of lightyears.

#
# Problem 1
#

def nestEggFixed(salary, save, growthRate, years):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an
      integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at
      the end of each year.
    """
    # TODO: Your code here.
    n=0
    F=[(salary)*save*.01];
    while n+1<years:
        F.append(F[n]*(1+.01*growthRate)+F[0]);
        n=n+1;
    return F

        
        
    
    
    
    

def testNestEggFixed():
    salary     = 10000
    save       = 10
    growthRate = 15
    years      = 5
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2150.0, 3472.5, 4993.375, 6742.3812499999995]
#testNestEggFixed()
#
# Problem 2
#

def nestEggVariable(salary, save, growthRates):
    # TODO: Your code here.
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
      account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """
    n=0
    F=[(salary)*(save)*.01];
    while n+1<=len(growthRates)-1:
        F.append(F[n]*(1+.01*growthRates[n])+F[0]);
        n=n+1;
    return F



def testNestEggVariable0():
    salary      = 10000
    save        = 10
    growthRates = [3, 4, 5, 0, 3]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print('test 0')
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002]

    # TODO: Add more test cases here.
def testNestEggVariable1():
    salary= 20000
    save=5
    growthRates=[3,4,5,0,3]
    savingsRecord= nestEggVariable(salary,save,growthRates)
    print('test 1')
    print savingsRecord

def testNestEggVariable2():
    salary= 20000
    save=10
    growthRates=[3,4,5,0,3]
    savingsRecord= nestEggVariable(salary,save,growthRates)
    print('test 2')
    print savingsRecord

def testNestEggVariable3():
    salary= 30000
    save=10
    growthRates=[3,4,5,0,3]
    savingsRecord= nestEggVariable(salary,save,growthRates)
    print('test 3')
    print savingsRecord

##testNestEggVariable0();
##testNestEggVariable1();
##testNestEggVariable2();
##testNestEggVariable3();
#
# Problem 3
#

def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
      account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
      retirement.
    - return: a list of your retirement account value at the end of each year.
    """
    # TODO: Your code here.
    n=0
    F=[savings*(1+.01*growthRates[n])-expenses];
    for n in range(0,len(growthRates)-1):
        F.append(F[n]*(1+.01*growthRates[n+1])-expenses);
        n=n+1;
    return F


def testPostRetirement0():
    savings     = 100000
    growthRates = [10, 5, 0, 5, 1]
    expenses    = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print '\n PR 0= ',savingsRecord
    # Output should have values close to:
    # [80000.000000000015, 54000.000000000015, 24000.000000000015,
    # -4799.9999999999854, -34847.999999999985]

    # TODO: Add more test cases here.
def testPostRetirement1():
    savings     = 200000
    growthRates = [3, 5, 0, 5, 1,3,6,1,2,4,5,10]
    expenses    = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print '\n PR 1= ',savingsRecord

def testPostRetirement2():
    savings     = 100000
    growthRates = [10, 15, 10, 25, 11]
    expenses    = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print '\n PR 2= ',savingsRecord

##testPostRetirement0()
##testPostRetirement1()
##testPostRetirement2()

#
# Problem 4
#

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,
                    epsilon):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments
      while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments
      while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in
      the investment fund at the end of retirement.
    """
    # TODO: Your code here.
        #little check before the program is started;
    assert epsilon > 0, 'Episolon must be greater than zero, not ' + str(epsilon)

    savings = nestEggVariable(salary, save, preRetireGrowthRates)[-1]
    low = 0
    high = savings + epsilon
    guess = low+(low - high)/2.0 #mid point
    endRetirement = postRetirement(savings, postRetireGrowthRates, guess)[-1]
    
    while abs(endRetirement) > epsilon:
        if endRetirement > epsilon:     
            low = guess
        else:
            high = guess
        guess = low+(high - low)/2.0
        endRetirement = postRetirement(savings, postRetireGrowthRates, guess)[-1]
    return guess




#       Binary Search Example from the lecture for reference

'''def bsearch(growthRates, epsilon, growthRates[n], len(growthRates)-1, calls):
                               print growthRates,len(growthRates)-1 , calls
                                if (last - first) < 2: return s[first] == e or s[last] == e
                                mid = first + (last - first)/2
                                if s[mid] == e: return True
                                if s[mid] > e: return bsearch(s, e, first, mid - 1, calls+1)
                                return bsearch(s, e, mid + 1, last, calls + 1)
                             '''   



def testFindMaxExpenses0():
    salary                = 10000
    save                  = 10
    preRetireGrowthRates  = [3, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0, 5, 1]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print 'findMax0= ',expenses
def testFindMaxExpenses1():
    salary                = 100000
    save                  = 10
    import random;
    a=random.randrange(0,15,1)
    preRetireGrowthRates  = [a]
    while len(preRetireGrowthRates)<20:
        preRetireGrowthRates.append(a);
    postRetireGrowthRates = [10, 5, 0, 5, 1,4,2,9,4]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print 'findMax1= ',expenses
def testFindMaxExpenses2():
    salary                = 30000
    save                  = 10
    import random;
    a=random.randrange(0,15,1)
    preRetireGrowthRates  = [a]
    while len(preRetireGrowthRates)<20:
        preRetireGrowthRates.append(a);
    postRetireGrowthRates = [10, 5, 0, 5, 1]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print 'findMax2= ',expenses



testFindMaxExpenses0()
testFindMaxExpenses1()
testFindMaxExpenses2()

    # Output should have a value close to:
    # 1229.95548986

    # TODO: Add more test cases here.

chrcoe (Self-grade: Outstanding)
Submitted 2 years ago | Permalink
# Problem Set 4
# Name: Chris Coe
# Time: 2:10 min total

#
# Problem 1 - 30 min
#

def nestEggFixed(salary, save, growthRate, years):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an
      integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at
      the end of each year.
    """
    sizeOfAccount = []
    #End of year 1
    sizeOfAccount.append(salary * save * 0.01)
    #End of year 2
    #sizeOfAccount.append(sizeOfAccount[0] * (1 + 0.01 * growthRate) + salary * save * 0.01)
    #End of year 3
    #sizeOfAccount.append(sizeOfAccount[1] * (1 + 0.01 * growthRate) + salary * save * 0.01)
    for yr in range(1,years):
        sizeOfAccount.append(sizeOfAccount[yr-1] * (1 + 0.01 * growthRate) + salary * save * 0.01)
    return sizeOfAccount

#print nestEggFixed(10000,10,15,5)

def testNestEggFixed():
    salary     = [10000,15000,20654]
    save       = [5,10,15]
    growthRate = [2,4,10]
    years      = [5,10,15]
    for count in range(0,3):
        print 'salary($):',salary[count],'save(% of salary):',save[count],'growthRate(%):',growthRate[count],'years:',years[count]
        savingsRecord = nestEggFixed(salary[count], save[count], growthRate[count], years[count])        
        print savingsRecord
        print
    # Output (for 10000,10,15,5) should have values close to:
    # [1000.0, 2150.0, 3472.5, 4993.375, 6742.3812499999995]

    # Added for loop to have multiple cases tested

#testNestEggFixed()

#
# Problem 2 - 20
#

def nestEggVariable(salary, save, growthRates):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
      account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """
    sizeOfAccount = []

    saveFromSalary = salary * save * 0.01
    sizeOfAccount.append(saveFromSalary)

    for yr in range(1,len(growthRates)):
        sizeOfAccount.append(sizeOfAccount[yr-1] * (1 + 0.01 * growthRates[yr-1]) + saveFromSalary)
    return sizeOfAccount

def testNestEggVariable():
    salary     = [10000,15000,20654]
    save       = [5,10,15]
    #growthRates = [3, 8, 2, 0, -3, 1, 3]
    growthRates = [-3,-3,-4]
    for c in range(0,len(salary)):
        print 'salary($):',salary[c],'save(% of salary):',save[c],'growthRates(% each year):',growthRates
        savingsRecord = nestEggVariable(salary[c], save[c], growthRates)
        print savingsRecord
        print
    # Output should have values close to:
    # [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002]

    # changed to a for loop and tested with additional years and negative growth years

#testNestEggVariable()

#
# Problem 3 - 10 min
#

def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
      account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
      retirement.
    - return: a list of your retirement account value at the end of each year.
    """
    sizeOfAccount = []

    sizeOfAccount.append(savings * (1 + 0.01*growthRates[0]) - expenses)

    for yr in range(1,len(growthRates)):
        sizeOfAccount.append(sizeOfAccount[yr-1] * (1 + 0.01 * growthRates[yr]) - expenses)
    return sizeOfAccount

def testPostRetirement():
    savings     = [100000,500000,1000000]
    growthRates = [10, 5, 0, 5, -1, -2, 1, 3, 2]
    expenses    = [30000,28000,25000]

    for c in range(0,len(savings)):
        print 'savings($):',savings[c],'growthRates(% each year):',growthRates,'expenses($/year):', expenses[c]
        savingsRecord = postRetirement(savings[c], growthRates, expenses[c])
        print savingsRecord
        print
    # Output should have values close to:
    # [80000.000000000015, 54000.000000000015, 24000.000000000015,
    # -4799.9999999999854, -34847.999999999985]

    #for loop to test multiple situations, added more years, pos and neg

#testPostRetirement()

#
# Problem 4 - 70 min
#

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,
                    epsilon):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments
      while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments
      while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in
      the investment fund at the end of retirement.
    """
    assert epsilon > 0, 'epsilon must be positive, not' + str(epsilon)

    savings = nestEggVariable(salary, save, postRetireGrowthRates)[-1] #savings at end of retirement
    low = 0
    high = savings + epsilon
    currentEstimate = (low + high)/2.0 #current estimate of allowable expenses
    endRetirement = postRetirement(savings, postRetireGrowthRates, currentEstimate)[-1] #
    #print 'Starting Savings:',savings,'\n'
    #print 'End of retirement guess:',endRetirement,'\n'
    
    while abs(endRetirement) > epsilon:
        if endRetirement < 0:     
            high = currentEstimate
        else:
            low = currentEstimate
        currentEstimate = (high + low)/2.0
        endRetirement = postRetirement(savings, postRetireGrowthRates, currentEstimate)[-1]
        print currentEstimate #current estimate for the amount of expenses on each iteration
        #print endRetirement
    return currentEstimate

def testFindMaxExpenses():
    salary                = 10000
    save                  = 10
    preRetireGrowthRates  = [3, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0, 5, 1]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses
    # Output should have a value close to:
    # 1229.95548986

##    My Output (supposed to print estimate during each iteration):
##        1353.815
##        676.9075
##        1015.36125
##        1184.588125
##        1269.2015625
##        1226.89484375
##        1248.04820312
##        1258.62488281
##        1263.91322266
##        1266.55739258
##        1265.23530762
##        1264.57426514
##        1264.90478638
##        1264.73952576
##        1264.82215607
##        1264.78084091
##        1264.76018333
##        1264.74985455
##        1264.74985455 #final answer

testFindMaxExpenses()
mrphud (Self-grade: Outstanding)
Submitted 2 years ago | Permalink
##Problem #1
#The following function implements a savings model with fixed growthrate
#and retirement contribution.

def nestEggFixed(salary, save, growthRate, years):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an
      integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at
      the end of each year.
    """
    retirement = [salary*save*0.01,]        #initiate the retirement fund
    time = 1                                #set the ctr and add variable
    new = 0
    while time < years:
        #time < years because we must have a salary to grow interest
        new = retirement[-1]*(1 + 0.01*growthRate) + retirement[0]
        retirement.append(new)              #computes end of year gain and
        time += 1                           #adds it to retirment. Start next year
    return retirement                       #return list of growth

def testNestEggFixed():
    salary     = 10000
    save       = 10
    growthRate = 15
    years      = 5
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2150.0, 3472.5, 4993.375, 6742.3812499999995]

##Problem #2
#The following function implements a savings model with variable growthrate

def nestEggVariable(salary, save, growthRates):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
      account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """
    years = len(growthRates)
    retirement = [salary*save*0.01,]
    for annual in range(1,years):
        #it starts at year one, because money can't be added until a salary is earned.
        new = retirement[-1]*(1 + 0.01*growthRates[annual]) + retirement[0]
        retirement.append(new)
    return retirement

def testNestEggVariable():
    salary      = 10000
    save        = 10
    growthRates = [3, 4, 5, 0, 3]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002]

#This shows there is more than one way to skin a cat.

def nestEggVariable2(salary, save, growthRates):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
      account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """
    retirement = [salary*save*0.01,]        #initiate the retirement fund
    years = len(growthRates)
    time = 1                                #set the ctr
    while time < years:
        #time must be < years since indexing for lists starts at zero.
        new = retirement[-1]*(1 + 0.01*growthRates[time]) + retirement[0]
        retirement.append(new)              #computes end of year gain and
        time += 1                           #adds it to retirment. Start next year
    return retirement                       #return list of growth

def testNestEggVariable2():
    salary      = 10000
    save        = 10
    growthRates = [3, 4, 5, 0, 3]
    savingsRecord = nestEggVariable2(salary, save, growthRates)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002]

##Problem #3
#The following function now removes additions to retirement and incorporates constant expenses

def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
      account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
      retirement.
    - return: a list of your retirement account value at the end of each year.
    """
    years = len(growthRates)        #This function is basically the same from problem #2
    retirement = [savings,]
    for annual in range(0,years):       
        new = retirement[-1]*(1 + 0.01*growthRates[annual]) - expenses
        retirement.append(new)
    return retirement 

def testPostRetirement():
    savings     = 100000
    growthRates = [10, 5, 0, 5, 1]
    expenses    = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord
    # Output should have values close to:
    # [80000.000000000015, 54000.000000000015, 24000.000000000015,
    # -4799.9999999999854, -34847.999999999985]

##Problem #4
#Now we try a method that leaves us with zero retirement money upon passing
#This will make use of successive approximation.

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,
                    epsilon):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments
      while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments
      while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in
      the investment fund at the end of retirement.
    """
    retirement = nestEggVariable(salary, save, preRetireGrowthRates)
    #This will yield the total money accrued before retirement
    ctr = 0                         #setting variables for the calculation
    high = retirement[-1]
    low = 0
    expense = (high + low)/2.0      #initial guess
    while ctr < 100:                #max number of iterations
        downturn = postRetirement(retirement[-1], postRetireGrowthRates, expense)
        #downturn is the result to check
        #print high, '', low, '', expense, '', downturn[-1], '', ctr
        if downturn[-1] < 0:    #if less than zero we are spending too much
            high = expense      #therefore reduce the high and check again
            expense = (high + low)/2.0 
            ctr += 1
        elif downturn[-1] > 0 and (downturn[-1] - 0) < epsilon:
            return expense
        #if downturn is positive and has a change less than epsilon we have converged
        else:                   #otherwise we are not spending as much as we can. 
            low = expense
            expense = (high + low)/2.0
            ctr += 1
    print 'Error: The calculation did not converge'         #Just in case
    print 'Try reducing the range or increasing the number of iterations'
        
def testFindMaxExpenses():
    salary                = 10000
    save                  = 10
    preRetireGrowthRates  = [3, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0, 5, 1]
    epsilon               = .001
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses
    # Output should have a value close to:
    # 1229.95548986

dimebucker (Self-grade: Pretty good)
Submitted 2 years ago | Permalink
# Problem Set 4
# Name: Matt Coley
# Collaborators: 
# Time: 

#
# Problem 1
#

def nestEggFixed(salary, save, growthRate, years):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an
      integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at
      the end of each year.
    """
    fundGrowth = []
    for currYear in range(years):
        if currYear == 0:
            fundGrowth.append(salary * save * 0.01)
        else:
            fundGrowth.append(fundGrowth[currYear-1] * (1 + 0.01 * growthRate) + salary * save * 0.01)
    return fundGrowth

#
# Problem 2
#

def nestEggVariable(salary, save, growthRates):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
      account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """
    fundGrowth = []
    for currYear in range(len(growthRates)):
        if currYear == 0:
            fundGrowth.append(salary * save * 0.01)
        else:
            fundGrowth.append(fundGrowth[currYear-1] * (1 + 0.01 * growthRates[currYear]) + salary * save * 0.01)
    return fundGrowth

#
# Problem 3
#

def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
      account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
      retirement.
    - return: a list of your retirement account value at the end of each year.
    """
    retireFund = []
    for currYear in range(len(growthRates)):
        if currYear == 0:
            retireFund.append(savings * (1 + 0.01 * growthRates[currYear]) - expenses)
        else:
            retireFund.append(retireFund[currYear-1] * (1 + 0.01 * growthRates[currYear]) - expenses)
    return retireFund

#
# Problem 4
#

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,
                    epsilon):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments
      while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments
      while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in
      the investment fund at the end of retirement.
    """
    savings = nestEggVariable(salary, save, preRetireGrowthRates)[len(preRetireGrowthRates)-1]
    low = 0
    high = savings
    guess = (low + high)/2.0
    ctr = 1
    finalSavings = postRetirement(savings, postRetireGrowthRates, guess)[len(postRetireGrowthRates)-1]
    while abs(finalSavings) > epsilon and ctr <= 100:
        #print 'finalSavings:', finalSavings, ' guess:', guess, ' high:', high, ' low:', low
        if finalSavings < 0:
            high = guess
        else:
            low = guess
        guess = (low + high)/2
        finalSavings = postRetirement(savings, postRetireGrowthRates, guess)[len(postRetireGrowthRates)-1]
        ctr += 1
    return guess
chip (Self-grade: Outstanding)
Submitted 2 years ago | Permalink
# Problem Set 4
# Name: chip
# Time: 0:45

#
# Problem 1
#

def nestEggFixed(salary, save, growthRate, years):
    assert type(years) == type(1) and years > 0, "Years must integer and > 0"
    retirement = [salary * save * 0.01]
    startyear = 1
    while startyear < years:
            retirement.append(retirement[-1] * (1 + 0.01 * growthRate) + salary * save * 0.01)
            startyear += 1
    return retirement 

#
# Problem 2
#

def nestEggVariable(salary, save, growthRates):
    retitement = [salary * save * 0.01]
    del growthRates[0]
    for rate in growthRates:
        retitement.append(retitement[-1] * (1 + 0.01 * rate) + salary * save * 0.01)
    return retitement

#
# Problem 3
#

def postRetirement(savings, growthRates, expenses):
    retitement = [savings * (1 + 0.01 * growthRates[0]) - expenses]
    i = 1
    while i < len(growthRates):
        retitement.append(retitement[-1] * (1 + 0.01 * growthRates[i]) - expenses)
        i += 1
    return retitement

#
# Problem 4
#

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates, epsilon):
    years = len(preRetireGrowthRates)
    savings = nestEggVariable(salary, save, preRetireGrowthRates)[years - 1]
    low = 0
    height = savings
    gues = (height + low) / 2
    rest = postRetirement(savings, postRetireGrowthRates, gues)[years - 1]
    while abs(rest) > epsilon:
        if rest > 0:
            low = gues
        else:
            height = gues
        gues = (height + low) / 2
        rest = postRetirement(savings, postRetireGrowthRates, gues)[years - 1]
    return gues

def testNestEggFixed():
    salary     = 10000
    save       = 10
    growthRate = 15
    years      = 5
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2150.0, 3472.5, 4993.375, 6742.3812499999995]

def testNestEggVariable():
    salary      = 10000
    save        = 10
    growthRates = [3, 4, 5, 0, 3]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002]

def testPostRetirement():
    savings     = 100000
    growthRates = [10, 5, 0, 5, 1]
    expenses    = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord
    # Output should have values close to:
    # [80000.000000000015, 54000.000000000015, 24000.000000000015,
    # -4799.9999999999854, -34847.999999999985]

def testFindMaxExpenses():
    salary                = 10000
    save                  = 10
    preRetireGrowthRates  = [3, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0, 5, 1]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses
    # Output should have a value close to:
    # 1229.95548986

testNestEggFixed()
testNestEggVariable()
testPostRetirement()
testFindMaxExpenses()
Joe (Self-grade: Outstanding)
Submitted 2 years ago | Permalink

Simulating a retirement fund

# Problem Set 4
# Name: Joe Li
# Time: 4:15

#
# Problem 1
#

# Retirement fund
# End of year 1
# F[0] = salary*save*0.01
# End of year 2
# F[1] = F[0]*(1+0.01*growthRate)+salary*save*0.01
# End of year 3
# F[2] = F[1]*(1+0.01*growthRate)+salary*save*0.01
        
def nestEggFixed(salary, save, growthRate, years):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
    year (an inte
    ger between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an
    integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at
    the end of each year.
    """
    assert 0<=save<=100 and type(save)==int, 'save is an integer between 0 and 100, not '+str(save)
    for r in growthRates:
        assert 0<=r<=100 and type(r)==int, 'elements in growthRates is an integer between 0 and 100, not '+str(r)
    # F(n,,,)is the size of retirement account at the end of nth year
    def F(n, salary, save, growthRate):
        if n==0:
            return salary*save*0.01
        else:
            return F(n-1, salary, save, growthRate)*(1+0.01*growthRate)+F(0, salary, save, growthRate)
    balance=[]
    for n in range(0,years):
        # append F[n] to list balance
        balance.append(F(n,salary,save,growthRate))
    return balance

def testNestEggFixed():
    salary     = 10000
    save     = 10
    growthRate = 15
    years    = 5
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2150.0, 3472.5, 4993.375, 6742.3812499999995]

    # TODO: Add more test cases here.

#
# Problem 2
#

def nestEggVariable(salary, save, growthRates):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
    year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
    account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """
    assert 0<=save<=100 and type(save)==int, 'save is an integer between 0 and 100, not '+str(save)
    for r in growthRates:
        assert 0<=r<=100 and type(r)==int, 'elements in growthRates is an integer between 0 and 100, not '+str(r)
    def F(n, salary, save, growthRates):
    # F(n,,,) is the size of retirement account at the end of nth year
    # it's a little bit different from the previous one
    # now the argument 'growthRates' is a list
    # the function will automatically choose the nth element in 'growthRates' to be the growthRate
        if n==0:
            return salary*save*0.01
        else:
            return F(n-1, salary, save, growthRates)*(1+0.01*growthRates[n])+F(0, salary, save, growthRates)

    balance=[]
    years=len(growthRates)
    # The length of the last argument defines the number of years you plan to work
    for n in range(0,years):
        # append F[n] to list balance
        balance.append(F(n,salary,save,growthRates))
    return balance

def testNestEggVariable():
    salary    = 10000
    save      = 10
    growthRates = [3, 4, 5, 0, 3]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002]

    # TODO: Add more test cases here.

#
# Problem 3
#



def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
    account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
    retirement.
    - return: a list of your retirement account value at the end of each year.
    """
    for r in growthRates:
        assert 0<=r<=100 and type(r)==int, 'elements in growthRates is an integer between 0 and 100, not '+str(r)
    def F(n,savings,growthRates,expenses):
        if n==0:
            return savings*(1+0.01*growthRates[0])-expenses
        else:
            return F(n-1,savings,growthRates,expenses)*(1+0.01*growthRates[n])-expenses
            # Retirement fund
            # End of year 1
            # F[0] = savings*(1+0.01*growthRates[0])-expenses
            # End of year 2
            # F[1] = F[0]*(1+0.01*growthRates[1])-expenses
            # End of year 3
            # F[2] = F[1]*(1+0.01*growthRates[2])-expenses
    balance=[]
    years=len(growthRates)
    # The length of the last argument defines the number of years you plan to work
    for n in range(0,years):
        balance.append(F(n,savings,growthRates,expenses))
    return balance

def testPostRetirement():
    savings     = 100000
    growthRates = [10, 5, 0, 5, 1]
    expenses    = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord
    # Output should have values close to:
    # [80000.000000000015, 54000.000000000015, 24000.000000000015,
    # -4799.9999999999854, -34847.999999999985]

    # TODO: Add more test cases here.

#
# Problem 4
#

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,epsilon):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
    year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments
    while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments
    while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in
    the investment fund at the end of retirement.
    """
    assert 0<=save<=100 and type(save)==int, 'save is an integer between 0 and 100, not '+str(save)
    for r in preRetireGrowthRates:
        assert 0<=r<=100 and type(r)==int, 'elements in preRetireGrowthRates is an integer between 0 and 100, not '+str(r)    
    for r in postRetireGrowthRates:
        assert 0<=r<=100 and type(r)==int, 'elements in postRetireGrowthRates is an integer between 0 and 100, not '+str(r)    
    savings=nestEggVariable(salary,save,preRetireGrowthRates)    # get the savings from the result of the function in problem 2
    savings=savings[-1]    # only balance of the last year before retirement is needed
    low=0
    high=savings
    expenses=(low+savings)/2.0
    ctn=0
    while abs(postRetirement(savings, postRetireGrowthRates, expenses)[-1])>epsilon:
        # if the epsilon requirement isn't met    
        assert ctn<=100, 'Interation limit exeeds'
        ctn+=1
        if postRetirement(savings, postRetireGrowthRates, expenses)[-1]>0:
            # if the expenses is too low  
            low=expenses    # higher the lower bound  
        else:
            # if the expenses is too high  
            high=expenses   # lower the upper bound  
        expenses=(low+high)/2.0 #reassign expenses
        print 'Interation',ctn,'expenses',expenses
    return expenses
    

def testFindMaxExpenses():
    salary            = 10000
    save            = 10
    preRetireGrowthRates  = [3, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0, 5, 1]
    epsilon           = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                     postRetireGrowthRates, epsilon)
    print expenses
    # Output should have a value close to:
    # 1229.95548986

    # TODO: Add more test cases here.
BTheMad (Self-grade: Could be better)
Submitted 2 years ago | Permalink
#
# Problem 1
#
def nestEggFixed(salary, save, growthRate, years):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an
      integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at
      the end of each year.
    """
    savings = [salary * save * 0.01]
    cur_savings = 0
    for cur_year in range(1, years):
        cur_savings = savings[cur_year - 1] * (1 + 0.01 * growthRate) \
                      + salary * save * 0.01
        savings.append(cur_savings)
    return savings

def testNestEggFixed():
    salary = 10000
    save = 10
    growthRate = 15
    years = 5
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2150.0, 3472.5, 4993.375, 6742.3812499999995]


#
# Problem 2
#
def nestEggVariable(salary, save, growthRates):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
      account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """
    savings = [salary * save * 0.01]
    cur_savings = 0
    for cur_year in range(1, len(growthRates)):
        cur_savings = savings[cur_year - 1] * \
                      (1 + 0.01 * growthRates[cur_year]) \
                      + salary * save * 0.01
        savings.append(cur_savings)
    return savings

def testNestEggVariable():
    salary = 10000
    save = 10
    growthRates = [3, 4, 5, 0, 3]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002]


#
# Problem 3
#
def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
      account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
      retirement.
    - return: a list of your retirement account value at the end of each year.
    """
    saving_rec = [savings * (1 + 0.01 * growthRates[0]) - expenses]
    cur_savings = 0
    for cur_year in range(1, len(growthRates)):
        cur_savings = saving_rec[cur_year - 1] * \
                      (1 + 0.01 * growthRates[cur_year]) \
                      - expenses
        saving_rec.append(cur_savings)
    return saving_rec

def testPostRetirement():
    savings = 100000
    growthRates = [10, 5, 0, 5, 1]
    expenses = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord
    # Output should have values close to:
    # [80000.000000000015, 54000.000000000015, 24000.000000000015,
    # -4799.9999999999854, -34847.999999999985]


#
# Problem 4
#
def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,
                    epsilon):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments
      while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments
      while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in
      the investment fund at the end of retirement.
    """
    num_of_years = len(preRetireGrowthRates)
    all_savings = nestEggVariable(salary, save, preRetireGrowthRates)
    savings = all_savings[num_of_years - 1]
    low = 0
    high = savings
    expenses = (high + low) / 2
    rest = postRetirement(savings, postRetireGrowthRates, expenses)[num_of_years - 1]
    while abs(rest) > epsilon:
        if rest > 0:
            low = expenses
        else:
            high = expenses
        expenses = (high + low) / 2
        all_rest = postRetirement(savings, postRetireGrowthRates, expenses)
        rest = all_rest[num_of_years - 1]
    return expenses

def testFindMaxExpenses():
    salary = 10000
    save = 10
    preRetireGrowthRates = [3, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0, 5, 1]
    epsilon = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses
    # Output should have a value close to:
    # 1229.95548986

    # TODO: Add more test cases here.

testFindMaxExpenses()
scarolan (Self-grade: Pretty good)
Submitted 2 years ago | Permalink

Should "growthRates" be all lower-case? My understanding is lower-case is conventional for variables.

#
# Problem 1
#

def nestEggFixed(salary, save, growthRate, years):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an
      integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at
      the end of each year.
    """
    # TODO: Your code here.
    yearlyreturn=[]
    nut = 0
    for i in range(0, years):
        # print "At the end of year",(i),"nut size is:",(round(nut,2))
        nut = nut * (1 + 0.01 * growthRate) + (salary * save * 0.01)
        # Rounded to two decimal places to make this easier to look at!
        yearlyreturn.append(round(nut,2))
    return yearlyreturn

def testNestEggFixed():
    salary     = 10000
    save       = 10
    growthRate = 15
    years      = 5
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2150.0, 3472.5, 4993.375, 6742.3812499999995]

    # TODO: Add more test cases here.
    salary     = 35000
    save       = 5
    growthRate = 3
    years      = 25
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord

    salary     = 85000
    save       = 10
    growthRate = 8
    years      = 10
    savingsRecord = nestEggFixed(salary, save, growthRate, years)    
    print savingsRecord

#
# Problem 2
#

def nestEggVariable(salary, save, growthRates):
    # TODO: Your code here.
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
      account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """
    yearlyreturn=[]
    nut = 0
    for i in range(0,len(growthRates)):
        # print "At the end of year",(i),"nut size is:",(round(nut,2))
        nut = nut * (1 + 0.01 * growthRates[i]) + (salary * save * 0.01)
        # Rounded to two decimal places to make this easier to look at!
        yearlyreturn.append(round(nut,2))
    return yearlyreturn

def testNestEggVariable():
    salary      = 10000
    save        = 10
    growthRates = [3, 4, 5, 0, 3]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002]

    # TODO: Add more test cases here.

    salary      = 100000
    save        = 8
    growthRates = [2, 4, 6, 4, 2]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord

    salary      = 35000
    save        = 3
    growthRates = [1, 2, 3, 4, 5]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord

#
# Problem 3
#

def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
      account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
      retirement.
    - return: a list of your retirement account value at the end of each year.
    """
    # TODO: Your code here.
    yearlysize = []
    for i in range(0, len(growthRates)):
        savings = savings * (1 + 0.01 * growthRates[i]) - expenses
        # print "In year",(i),"savings is",round(savings,2)
        yearlysize.append(round(savings,2))
    return yearlysize

def testPostRetirement():
    savings     = 100000
    growthRates = [10, 5, 0, 5, 1]
    expenses    = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord
    # Output should have values close to:
    # [80000.000000000015, 54000.000000000015, 24000.000000000015,
    # -4799.9999999999854, -34847.999999999985]

    # TODO: Add more test cases here.
    savings     = 25000000
    growthRates = [6, 6, 4, 6, 0]
    expenses    = 50000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord

    savings     = 50000
    growthRates = [12, 8, 4, 2, 1]
    expenses    = 3000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord

#
# Problem 4
#

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,
                    epsilon):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments
      while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments
      while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in
      the investment fund at the end of retirement.
    """
    # TODO: Your code here.
    startsave = nestEggVariable(salary, save, preRetireGrowthRates)[-1]
    low = 0
    high = startsave
    approx = (low + high)/2.0
    endsave = postRetirement(startsave, postRetireGrowthRates, approx)[-1]
    count = 1
    print approx
    while abs(endsave) > epsilon and count <=100:
        if endsave < 0:
            high = approx
        else:
            low = approx
        approx = (low + high) / 2.0
        print approx
        endsave = postRetirement(startsave, postRetireGrowthRates, approx)[-1]
        count += 1
    return round(approx,2)
    
def testFindMaxExpenses():
    salary                = 10000
    save                  = 10
    preRetireGrowthRates  = [3, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0, 5, 1]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses
    # Output should have a value close to:
    # 1229.95548986

    # TODO: Add more test cases here.
    salary                = 100000
    save                  = 5
    preRetireGrowthRates  = [2, 4, 5, 4, 2]
    postRetireGrowthRates = [8, 5, 0, 5, 1]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses    

    salary                = 85000
    save                  = 8
    preRetireGrowthRates  = [8, 8, 9, 5, 4]
    postRetireGrowthRates = [2, 2, 2, 2, 1]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses
jyen (Self-grade: Pretty good)
Submitted 2 years ago | Permalink
# Problem Set 4
# Name: jyen
# Time: 1 hour

#
# Problem 1
#

def nestEggFixed(salary, save, growthRate, years):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an
      integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at
      the end of each year.
    """
    savings = [salary * save * .01]
    for n in range (1, years):
        year = (savings[n - 1] * (1 + .01 * growthRate) + (salary * save * .01))
        savings.append (year)
    return savings

def testNestEggFixed():
    salary     = 10000
    save       = 10
    growthRate = 15
    years      = 5
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2150.0, 3472.5, 4993.375, 6742.3812499999995]

    # TODO: Add more test cases here.

#
# Problem 2
#

def nestEggVariable(salary, save, growthRates):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
      account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """
    savings = []
    year = 0
    for rate in growthRates:
        year = year * (1 + .01 * rate) + (salary * save * .01)
        savings.append(year)
    return savings

def testNestEggVariable():
    salary      = 10000
    save        = 10
    growthRates = [3, 4, 5, 0, 3]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002]

    # TODO: Add more test cases here.

#
# Problem 3
#

def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
      account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
      retirement.
    - return: a list of your retirement account value at the end of each year.
    """
    funds = []
    year = savings
    for rate in growthRates:
        year = year * (1 + .01 * rate) - expenses
        funds.append(year)
    return funds

def testPostRetirement():
    savings     = 100000
    growthRates = [10, 5, 0, 5, 1]
    expenses    = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord
    # Output should have values close to:
    # [80000.000000000015, 54000.000000000015, 24000.000000000015,
    # -4799.9999999999854, -34847.999999999985]

    # TODO: Add more test cases here.

#
# Problem 4
#

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,
                    epsilon):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments
      while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments
      while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in
      the investment fund at the end of retirement.
    """
    savings = nestEggVariable(salary, save, preRetireGrowthRates)
    nestegg = savings[-1]

    low = 0
    high = nestegg
    finalBalance = nestegg

    while abs(finalBalance) > epsilon:
        expenses = (high + low) / 2.0
        print 'Testing for expenses at ', expenses
        finalBalance = postRetirement(nestegg, postRetireGrowthRates, expenses)[-1]
        print 'Final balance is ', finalBalance
        if finalBalance > 0:
            low = expenses
        else:
            high = expenses
    return expenses
        
def testFindMaxExpenses():
    salary                = 10000
    save                  = 10
    preRetireGrowthRates  = [3, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0, 5, 1]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses
    # Output should have a value close to:
    # 1229.95548986

    # TODO: Add more test cases here.
hendrix (Self-grade: Pretty good)
Submitted 2 years ago | Permalink

I haven't watched lecture 6 yet but I thought I'd have a look at the problem set and just carried on. I used the bisection method from lecture 5 in my solution to problem 4 and it seems to work fine.

#
# Problem 1
#

def percentage(value):
    percentage = float(value)/100
    return percentage

def nestEggOneYear(salary, save):
    yearsSavings = salary * percentage(save)
    return yearsSavings

def nestEggFixed(salary, save, growthRate, years):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an
      integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at
      the end of each year.
    """
    currentYear = 0
    fundValues = []
    while currentYear <= years:
        if currentYear == years:
            return fundValues
        elif currentYear == 0:
            fundValues.append(nestEggOneYear(salary, save))
            currentYear += 1
        else:
            fundValues.append((fundValues[currentYear - 1] * (1 + percentage(growthRate)))\
            + nestEggOneYear(salary, save))
            currentYear += 1
    return fundValues
            
def testNestEggFixed():
    salary     = 10000
    save       = 10
    growthRate = 15
    years      = 5
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2150.0, 3472.5, 4993.375, 6742.3812499999995]

    # TODO: Add more test cases here.

#testNestEggFixed()

#
# Problem 2
#

def nestEggVariable(salary, save, growthRates):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
      account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """
    currentYear = 0
    numberOfYears = len(growthRates)
    fundValues = []
    while currentYear <= numberOfYears:
        if currentYear == numberOfYears:
            return fundValues
        elif currentYear == 0:
            fundValues.append(nestEggOneYear(salary, save))
            currentYear += 1
        else:
            fundValues.append((fundValues[currentYear - 1] * 
            (1 + percentage(growthRates[currentYear]))) + 
            nestEggOneYear(salary, save))
            currentYear += 1
    return fundValues


def testNestEggVariable():
    salary      = 10000
    save        = 10
    growthRates = [3, 4, 5, 0, 3]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002]

    # TODO: Add more test cases here.

#testNestEggVariable()

#
# Problem 3
#

def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
      account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
      retirement.
    - return: a list of your retirement account value at the end of each year.
    """
    
    def postRetirementOneYear(savings, growthRate, expenses):
        """
        helper function to calculate one years fund size
        """
        fundSize = (savings * (1 + percentage(growthRate))) - expenses
        return fundSize
    
    currentYear = 0
    numberOfYears = len(growthRates)
    fundValues = []
    while currentYear <= numberOfYears:
        if currentYear == numberOfYears:
            return fundValues
        elif currentYear == 0:
            fundValues.append(postRetirementOneYear(savings, growthRates[0], expenses))
            currentYear += 1
        else:
            fundValues.append(postRetirementOneYear(fundValues[currentYear - 1]
            , growthRates[currentYear], expenses))
            currentYear += 1
    return fundValues

def testPostRetirement():
    savings     = 100000
    growthRates = [10, 5, 0, 5, 1]
    expenses    = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord
    # Output should have values close to:
    # [80000.000000000015, 54000.000000000015, 24000.000000000015,
    # -4799.9999999999854, -34847.999999999985]

    # TODO: Add more test cases here.


#testPostRetirement()

#
# Problem 4
#

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,
                    epsilon):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments
      while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments
      while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in
      the investment fund at the end of retirement.
    """
    fundValuesBeforeRetirement = nestEggVariable(salary, save, 
    preRetireGrowthRates)
    fundAtRetirement = fundValuesBeforeRetirement[-1]
    upperBound = fundAtRetirement
    lowerBound = 0
    def guessGenerator(upperBound, lowerBound):
        guess = (upperBound + lowerBound)/2.0
        return guess
    guess = guessGenerator(upperBound, lowerBound)
    print "current guess is %s" % guess
    def moneyAtDeath(fundAtRetirement, postRetireGrowthRates, guess):
        fundValuesAfterRetirement = postRetirement(fundAtRetirement, 
        postRetireGrowthRates, guess)
        fundValueAtDeath = fundValuesAfterRetirement[-1]
        #print "moneyAtDeath with this guess is %s" % fundValueAtDeath
        return fundValueAtDeath
    fundValueAtDeath = moneyAtDeath(fundAtRetirement, postRetireGrowthRates, guess)
    print fundValueAtDeath
    if abs(fundValueAtDeath) <= epsilon:
        return guess
    while abs(fundValueAtDeath) > epsilon:
        if fundValueAtDeath < 0:
            upperBound = guess
            guess = guessGenerator(upperBound, lowerBound)
            print "current guess is %s" % guess
            fundValueAtDeath = moneyAtDeath(fundAtRetirement, postRetireGrowthRates,
            guess)
        elif fundValueAtDeath > 0:
            lowerBound = guess
            guess = guessGenerator(upperBound, lowerBound)
            print "current guess is %s" % guess
            fundValueAtDeath = moneyAtDeath(fundAtRetirement, postRetireGrowthRates,
            guess)
    return guess


def testFindMaxExpenses():
    salary                = 10000
    save                  = 10
    preRetireGrowthRates  = [3, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0, 5, 1]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses
    # Output should have a value close to:
    # 1229.95548986

    # TODO: Add more test cases here.

#testFindMaxExpenses()
zpritchard (Self-grade: Pretty good)
Submitted 2 years ago | Permalink
###############
 ## Problem 1 ##
  ###############

def nestEggFixed(salary, save, growthRate, years):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an
      integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at
      the end of each year.
    """
    curBal = 0
    out = []
    for a in xrange(0,years):
        addint = curBal * (1 + growthRate * 0.01)
        addprinc = salary * save * 0.01
        curBal = addint + addprinc
        out.append(curBal)
    return out

  ###############
 ## Problem 2 ##
###############

def nestEggVariable(salary, save, growthRates):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
      account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """
    out = []
    curBal = 0
    for rate in growthRates:
        addint = curBal * (1 + rate * 0.01)
        addprinc = salary * save * 0.01
        curBal = addint + addprinc
        out.append(curBal)
    return out    

  #############
 ## Problem 3 ##
#################

def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
      account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
      retirement.
    - return: a list of your retirement account value at the end of each year.
    """
    out = []
    curBal = savings
    for rate in growthRates:
        curBal = curBal * (1 + 0.01 * rate) - expenses
        out.append(curBal)
    return out

#################
 ## Problem 4 ##
  #############

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,
                    epsilon):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments
      while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments
      while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in
      the investment fund at the end of retirement.
    """
    preRetire = nestEggVariable(salary, save, preRetireGrowthRates)
    bal = preRetire[-1]

    hi = bal
    lo = 0
    count = 0
    finalBal = bal
    while abs(finalBal) > epsilon and count <=100:
        expenses = (hi + lo) / 2
        postRetire = postRetirement(bal, postRetireGrowthRates, expenses)
        finalBal = postRetire[-1]
        print 'Iteration',str(count) + ',','Expense estimate:',expenses
        if finalBal > epsilon:
            lo = expenses
        elif finalBal < -epsilon:
            hi = expenses
        count += 1
    return expenses
klaymen (Self-grade: Pretty good)
Submitted 3 years ago | Permalink

it's pretty sloppy as i was in a rush to catch up (haven't had a computer to work with for a while), but it works

# Problem Set 4
# Name: 
# Collaborators: 
# Time: 

#
# Problem 1
#

def nestEggFixed(salary, save, growthRate, years):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an
      integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at
      the end of each year.
    """
    # TODO: Your code here.
    assert type(save) == int, "savings must be an integer"
    assert type(salary) == int, "salary must be an integer"
    assert type(growthRate) == int, "growthRate must be an integer"
    assert type(years) == int, "years must be an integer"
    retireSize = [0]
    ctr = years
    while ctr > 0:
        retireSize += [retireSize[-1] + (salary*(save/100.0)) + (retireSize[-1]*(growthRate/100.0))]
        ctr = ctr - 1
    retireSize = tuple(retireSize[1:])
    return retireSize
    

def testNestEggFixed():
    salary     = 10000
    save       = 10
    growthRate = 15
    years      = 5
    #tested all variables as strings
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2150.0, 3472.5, 4993.375, 6742.3812499999995]

    # TODO: Add more test cases here.
    

#
# Problem 2
#

def nestEggVariable(salary, save, growthRates):
    # TODO: Your code here.
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
      account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """
    retireSize = [0]
    assert type(save) == int, "savings must be an integer"
    assert type(salary) == int, "salary must be an integer"
    for n in growthRates:
        assert type(n) == int, "all growthRates must be integers"
        retireSize += [retireSize[-1] + (salary*(save/100.0)) + (retireSize[-1]*(n/100.0))]
    retireSize = retireSize[1:]
    return retireSize
        

def testNestEggVariable():
    salary      = 10000
    save        = 10
    growthRates = [3, 4, 5, 0, 3]
    #all variables tested as strings
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002]

    # TODO: Add more test cases here.

#
# Problem 3
#

def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
      account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
      retirement.
    - return: a list of your retirement account value at the end of each year.
    """
    # TODO: Your code here.
    assert type(savings) == int, "savings must be an integer"
    assert type(expenses) == int, "expenses must be an integer"
    moneypot = [savings]
    for n in growthRates:
        assert type(n) == int, "all growthRates must be integers"
        moneypot += [(moneypot[-1])+((n/100.0)*moneypot[-1])- expenses]
    moneypot = moneypot[1:]
    return moneypot

def testPostRetirement():
    savings     = 100000
    growthRates = [10, 5, 0, 5, 1]
    expenses    = 30000
    #all variables tested as strings
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord
    # Output should have values close to:
    # [80000.000000000015, 54000.000000000015, 24000.000000000015,
    # -4799.9999999999854, -34847.999999999985]

    # TODO: Add more test cases here.

#
# Problem 4
#

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,
                    epsilon):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments
      while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments
      while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in
      the investment fund at the end of retirement.
    """
    # TODO: Your code here.

    assert type(salary) == int and salary > 0, "salary must be a positive integer"
    assert type(save) == int and save > 0, "save must be a positive integer"
    assert epsilon > 0, "epsilon must be a positive integer"
    preR = [0]
    postR = [preR[-1]]
    combined = []
    ctr = 0
    low = 0
    high = salary
    estimate = (low+high)/2.0


    for n in preRetireGrowthRates:
        assert type(n) == int, "all growthRates must be integers"
        preR += [(preR[-1] + (salary*(save/100.0)) + (preR[-1]*(n/100.0)))]
        postR = [preR[-1]]
    
    while abs(postR[-1]) > epsilon:
        assert type(n) == int, "all growthRates must be integers"
        postR = [preR[-1]]
        estimate = (low+high)/2.0
        for n in postRetireGrowthRates:
            postR += [((postR[-1])+((n/100.0)*postR[-1])) - estimate]
        if postR[-1] > epsilon:
            low = estimate
        else:
            high = estimate
        ctr += 1
##        print 'est: ', estimate
##        print 'low: ', low
##        print 'high: ', high
##        print 'preR: ', preR
##        print 'postR: ', postR
##        print 'janks: ', postR[-1]
##        print '-------------------------------------------------------------------------'
##        assert ctr <= 50, 'counter exceeded'
    return estimate
            
    
    

def testFindMaxExpenses():
    salary                = 10000
    save                  = 10
    preRetireGrowthRates  = [3, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0, 5, 1]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses
    # Output should have a value close to:
    # 1229.95548986

    # TODO: Add more test cases here.

Comments:

klaymen
3 years ago

also, this was due last lecture

klaymen
3 years ago

updated for my own reasons

# Problem Set 4
# Name: 
# Collaborators: 
# Time: 

#
# Problem 1
#

def nestEggFixed(salary, save, growthRate, years):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an
      integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at
      the end of each year.
    """
    # TODO: Your code here.
    moneypot = [0]
    while years > 0:
        moneypot += [(moneypot[-1])+((save/100.0)*salary)+((growthRate/100.0)*moneypot[-1])]
        years -= 1
    return moneypot[1:]

def testNestEggFixed():
    salary     = 10000
    save       = 10
    growthRate = 15
    years      = 5
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2150.0, 3472.5, 4993.375, 6742.3812499999995]

    # TODO: Add more test cases here.

#
# Problem 2
#

def nestEggVariable(salary, save, growthRates):
    # TODO: Your code here.
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
      account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """
    moneypot = [0]
    for n in growthRates:
        moneypot += [(moneypot[-1])+((save/100.0)*salary)+((n/100.0)*moneypot[-1])]
    return moneypot[1:]

def testNestEggVariable():
    salary      = 10000
    save        = 10
    growthRates = [3, 4, 5, 0, 3]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002]

    # TODO: Add more test cases here.

#
# Problem 3
#

def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
      account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
      retirement.
    - return: a list of your retirement account value at the end of each year.
    """
    # TODO: Your code here.
    moneypot = [savings]
    for n in growthRates:
        moneypot += [(moneypot[-1])+((n/100.0)*moneypot[-1])-expenses]
    return moneypot[1:]

def testPostRetirement():
    savings     = 100000
    growthRates = [10, 5, 0, 5, 1]
    expenses    = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord
    # Output should have values close to:
    # [80000.000000000015, 54000.000000000015, 24000.000000000015,
    # -4799.9999999999854, -34847.999999999985]

    # TODO: Add more test cases here.

#
# Problem 4
#

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,
                    epsilon):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments
      while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments
      while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in
      the investment fund at the end of retirement.
    """
    # TODO: Your code here.
    ctr = 0
    high = salary
    low = 0

    savings = nestEggVariable(salary, save, preRetireGrowthRates)[-1]
    while ctr <= 20:
        guess = (high+low)/2.0
        if postRetirement(savings, postRetireGrowthRates, guess)[-1] < 0:
            high = guess
        else: low = guess
        if abs(postRetirement(savings, postRetireGrowthRates, guess)[-1]) < epsilon: return guess
        ctr += 1
##        print 'g', guess
##        print 'h', high
##        print 'l', low
        
    return "counter limit exceeded"
            
        
    


def testFindMaxExpenses():
    salary                = 10000
    save                  = 10
    preRetireGrowthRates  = [3, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0, 5, 1]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses
    # Output should have a value close to:
    # 1229.95548986

    # TODO: Add more test cases here.

Sign up or log in to comment

Celauran (Self-grade: Outstanding)
Submitted 3 years ago | Permalink
#!/usr/bin/env python

def nestEggFixed(salary, save, growthRate, years):
    nestEgg = [salary * save * 0.01]
    for year in range(1, years):
        thisYear = nestEgg[year - 1] * (1 + 0.01 * growthRate) + salary * save * 0.01
        nestEgg.append(thisYear)
    return nestEgg

def nestEggVariable(salary, save, growthRates):
    nestEgg = []
    previous = 0
    for rate in growthRates:
        previous = previous * (1 + 0.01 * rate) + salary * save * 0.01
        nestEgg.append(previous)
    return nestEgg

def postRetirement(savings, growthRates, expenses):
    account = []
    previous = savings
    for rate in growthRates:
        previous = previous * (1 + 0.01 * rate) - expenses
        account.append(previous)
    return account

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates, epsilon):
    savings = nestEggVariable(salary, save, preRetireGrowthRates)[-1]
    low = 0
    high = savings
    guess = (low + high) / 2.0
    endBalance = postRetirement(savings, postRetireGrowthRates, guess)[-1]
    i = 1
    while abs(endBalance) > epsilon and i <= 100:
        if endBalance < 0:
            # expenses are too high
            high = guess
        else:
            # expenses are too low
            low = guess
        guess = (low + high) / 2.0
        endBalance = postRetirement(savings, postRetireGrowthRates, guess)[-1]
        i += 1
    return guess
shaggorama (Self-grade: Outstanding)
Submitted 3 years ago | Permalink
#!/usr/bin/env python
#-*- coding:utf-8 -*-

def nestEggFixed(salary, save, growthRate, years):
	"""
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an
      integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at
      the end of each year.
	"""
	F = []
	F.append(salary * save * 0.01)
	year = 1
	assert type(years) == int, "Years must be an integer"
	assert type(growthRate) == int, "Growthrate must be an integer"
	assert 0 <= years < 101, "Years must be between 0 and 100"
	assert 0 <= growthRate < 101, "Growthrate must be between 0 and 100"
	if years == 0:
		return F
	while (years > year):
		F.append(F[year-1] * (1 + 0.01 * growthRate) + salary * save * 0.01)
		year += 1
	return F



def testNestEggFixed():
    salary     = 10000
    save       = 10
    growthRate = 4
    years      = 5
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2150.0, 3472.5, 4993.375, 6742.3812499999995]

    # TODO: Add more test cases here.

# testNestEggFixed()

#
# Problem 2
#

def nestEggVariable(salary, save, growthRates):
	"""
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
      account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
	"""
	years = len(growthRates)
	F = []
	F.append(salary * save * 0.01)
	year = 0
	if years == 0:
		return F
	else:
		while years > year:
			if year == 0:
				year += 1
			else:
				growthRate = growthRates[year]
				assert type(growthRate) == int, "Growthrate must be an integer"
				assert 0 <= growthRate < 101, "Growthrate must be between 0 and 100"
				F.append(F[year-1] * (1 + 0.01 * growthRate) + salary * save * 0.01)
				year += 1
		return F

def testNestEggVariable():
	salary      = 10000
	save        = 10
	growthRates = [3, 4, 5, 0, 3]
	savingsRecord = nestEggVariable(salary, save, growthRates)
	print savingsRecord
    # Output should have values close to:
    # [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002]

    # TODO: Add more test cases here.

# testNestEggVariable()

#
# Problem 3
#

def postRetirement(savings, growthRates, expenses):
	"""
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
      account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
      retirement.
    - return: a list of your retirement account value at the end of each year.
	"""
	years = len(growthRates)
	F = []
	year = 0
	F.append(savings * (1 + 0.01 * growthRates[year]) - expenses)
	if years == 0:		
		return F
	else:
		while years > year:
			if year == 0:
				year += 1
			else:
				growthRate = growthRates[year]
				assert type(growthRate) == int, "Growthrate must be an integer"
				assert 0 <= growthRate < 101, "Growthrate must be between 0 and 100"
				F.append(F[year-1] * (1 + 0.01 * growthRates[year]) - expenses)
				year += 1
		return F


def testPostRetirement():
    savings     = 100000
    growthRates = [10, 5, 0, 5, 1]
    expenses    = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord
    # Output should have values close to:
    # [80000.000000000015, 54000.000000000015, 24000.000000000015,
    # -4799.9999999999854, -34847.999999999985]

#testPostRetirement()

#
# Problem 4
#

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates, epsilon):
	"""
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments
      while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments
      while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in
      the investment fund at the end of retirement.
	"""
	savings = nestEggVariable(salary, save, preRetireGrowthRates)[-1]
	high = savings + epsilon
	low = 0
	expenses = (high + low)/2
	end_balance = postRetirement(savings, postRetireGrowthRates, expenses)[-1]
	while abs(end_balance) > epsilon:
		if end_balance < 0:	
			high = expenses
		else:
			low = expenses
		expenses = (high + low)/2
		end_balance = postRetirement(savings, postRetireGrowthRates, expenses)[-1]
		print end_balance	
	return expenses



def testFindMaxExpenses():
    salary                = 10000
    save                  = 10
    preRetireGrowthRates  = [3, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0, 5, 1]
    epsilon               = .001
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses
    # Output should have a value close to:
    # 1229.95548986

testFindMaxExpenses()