Python Lesson
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.
This problem was fairly easy. I was actually quite surprised with myself in how fast I solved it. At first I stumped myself a bit, because I could easily understand how it could be solved recursively, however I couldn’t figure out how to write it. I’m still working on understanding the implementation of recursive functions, despite recognizing when they are more functionally viable. Here is my end function.
# salary = your starting salary # save = the percentage of your salary you put into retirement # growthRate = annual growth percentage of your retirement fund # fund = your retirement fund # returns a list with the value of the retirement fund at the end of each year def nestEggFixed(salary,save,growthRate,years): countyear = 1 base = salary*save*.01 F = [base,] while years > countyear: accountvalue = base + (1 + 0.01 * growthRate)*F[-1] F.append(accountvalue) countyear += 1 return F |
The hashtags at the beginning denote my code comments (or part of the file that is not actually taken into account when the code is processed). By reading my comments you will understand the designation of each variable.
Now comes the while loop, that processes my information and creates the list. Here I state that as long as the total ‘years’ I am going to work is less than my ‘countyear’ it should do the following. My function should create an ‘accountvalue’. ‘Accountvalue’ is the total value of my retirement account for that particular year. The equation that defines it includes the base investment, and the subsequent math needed to process it. What makes this whole thing work is ‘F[-1]’. Here I am taking a slice of the list F. In particular I am taking the last piece of that list, and then using it in my equation. This last item is the last item added to the list. In this case it’s the base investment. In subsequent runs through the function, it will be the last appended investment total of the account.
So what results to I obtain when processing this function?
Here are my variables: print nestEggFixed(10000,10,15,5) My results: [1000.0, 2150.0, 3472.5, 4993.375, 6742.381] |