### PS4: Problems 1–3 » Solutions

Jun. 3rd, 2010 01:42 pm**aranthe**posting in

**intro_to_cs**

Sorry these are late! I completely forgot that it was due this week.

Note: To simply readability, I've removed all of the triple-quoted comments found in the template and will post problem 4 separately because it's longer.

#### PS4 » Problem 1

def nestEggFixed(salary, save, growthRate, years): assert salary > 0, 'Salary must be greater than 0:' + str(salary) assert 0 < save < 100, 'Savings percentage must be between 0 and 100:' + str(savePct) assert 0 < growthRate < 100, 'Growth rate must be greater than 0:' + str(growthPct) assert years > 0, 'Years must be greater than 0:' + str(years) savingsRecord = [] # Initialize savings list. # Add one to years to capture last year. for year in range( 1, years+1 ): # First year is different. if( year == 1 ): savingsRecord.append( salary * save * 0.01 ) else: # savingsRecord[-1] is the savings at the end of the last year. savingsRecord.append( savingsRecord[-1] * (1 + 0.01 * growthRate) + salary * save * 0.01 ) return savingsRecord

#### PS4 » Problem 2

def nestEggVariable(salary, save, growthRates): assert salary > 0, 'Salary must be greater than 0:' + str(salary) assert 0 < save < 100, 'Savings percentage must be between 0 and 100:' + str(savePct) savingsRecord = [] # Initialize savings list. years = len(growthRates) # Compute number of years from input variable. # Add one to years to capture last year. for year in range( 1, years+1 ): # First year is different. if( year == 1 ): savingsRecord.append( salary * save * 0.01 ) else: # savingsRecord[-1] is the savings at the end of the last year. savingsRecord.append( savingsRecord[-1] * (1 + 0.01 * growthRates[year-1]) + salary * save * 0.01 ) return savingsRecord

#### PS4 » Problem 3

def postRetirement(savings, growthRates, expenses): assert savings > 0, 'Savings must be greater than 0:' + str(savings) fundBalances = [] # Initialize fund list. years = len(growthRates) # Compute number of years from input variable. # Add one to years to capture last year. for year in range( 1, years+1 ): # First year is different. if( year == 1 ): fundBalances.append( savings * (1 + 0.01 * growthRates[year-1]) - expenses ) else: # fundBalances[-1] is the fund at the end of the last year. fundBalances.append( fundBalances[-1] * (1 + 0.01 * growthRates[year-1]) - expenses ) return fundBalances