麻省理工学院公开课:计算机科学及编程导论习题4上

习题1:

写一个函数nestEggFixed,参数:工资salary、工资投资百分比save、投资账户的年增长率growthRate、工作年限;

返回一个数组,包含每一年账户资金,最后一年在最后位。

完全按下面来定义这个函数

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


第一年投资账户资金:salary * save

第二年投资账户资金: salary * save * (1 + growthRate) + salary * save

第三年投资账户资金:(salary * save * (1 + growthRate) + salary * save) *  (1 + growthRate) + salary * save


也就是除了第一年之外,其他年份都是上一年账户的资金 * (1 + 增长率) + 当年工资 * 投资百分比


原题save和growthrate都要除以100,这里直接当作百分比来处理,会看起来更简洁明了。


为了复习一下,用了递归,如果用迭代的话会很简单。

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

	def annual_save(salary, save):
		annual_save = salary * save
		return annual_save
	
	def annual_fund(salary, save, growthRate, years):
		if years > 0:
			years = years - 1
			annual_total = annual_fund(salary, save, growthRate, years) * (1 + growthRate) + annual_save(salary, save)
			return annual_total
		else:
			return 0
	
	fund = []
	for time in range(1, years + 1):
		fund.append(annual_fund(salary, save, growthRate, time))
	return fund



习题2:

写一个函数nestEggVariable,参数:工资salary、工资投资百分比save、投资账户的年增长率growthRates是一个数组,数组的长度表示工作年限,也就是说这个数组的范围是从工作第一年到工作最后一年;

返回一个数组,包含每一年账户资金。

完全按下面来定义这个函数

def nestEggVariable(salary, save, growthRates):


稍微改动下就可以。

def nestEggVariable(salary, save, growthRates):

	def annual_save(salary, save):
		annual_save = salary * save
		return annual_save
	
	def annual_fund_Variable(salary, save, growthRates):
		years = len(growthRates)
		if years > 0:
			years = years - 1
			annual_total = annual_fund_Variable(salary, save, growthRates[:years]) * (1 + growthRates[years]) + annual_save(salary, save)
			return annual_total
		else:
			return 0
	
	fund = []
	for time in range(0, len(growthRates)):
		fund.append(annual_fund_Variable(salary, save, growthRates[:time + 1]))
	return fund



你可能感兴趣的:(麻省理工学院公开课:计算机科学及编程导论习题4上)