MIT OCW 6.0001 課程 Problem Set 1 作業(yè)(Part B)
打卡記錄
打卡時(shí)間:2019.07.26
打卡天數(shù):D03
學(xué)習(xí)內(nèi)容:MIT OCW 6.0001 課程 Problem Set 1 作業(yè)(Part B)
參考鏈接
Part B 作業(yè):
Part B: Saving, with a raise
Background
In Part A, we unrealistically assumed that your salary didn’t change. But you are an MIT graduate, and clearly you are going to be worth more to your company over time! So we are going to build on your solution to Part A by factoring in a raise every six months.
In ps1b.py, copy your solution to Part A (as we are going to reuse much of that machinery). Modify your program to include the following
- Have the user input a semi-annual salary raise semi_annual_raise (as a decimal percentage)
- After the 6 th month, increase your salary by that percentage. Do the same after the 12 th month, the 18 th month, and so on.
Write a program to calculate how many months it will take you save up enough money for a down payment. LIke before, assume that your investments earn a return of r = 0.04 (or 4%) and the required down payment percentage is 0.25 (or 25%). Have the user enter the following variables:
- The starting annual salary (annual_salary)
- The percentage of salary to be saved (portion_saved)
- The cost of your dream home (total_cost)
- The semi-annual salary raise (semi_annual_raise)
作業(yè)心得
PartB的作業(yè)其實(shí)和PartA的整體思路差不多,主要是增加了一個(gè)變動(dòng)收入,沒(méi)6個(gè)月加薪
寫(xiě)一個(gè)程序用于計(jì)算 需要多少個(gè)月儲(chǔ)蓄才夠首付,大多數(shù)變量都需要float類(lèi)型,所以需要將用戶(hù)的輸入轉(zhuǎn)化為float,程序需要用戶(hù)輸入以下變量::
- 一開(kāi)始的年薪 (annual_salary)
- 每月存款的比例 (portion_saved)
- 房子的價(jià)錢(qián) (total_cost)
- 提薪的比率(semi_annual_raise)
整體的思路就是做一個(gè)循環(huán),每個(gè)迭代就是一個(gè)月,判斷當(dāng)月 的存款是否大于等于首付。
存款由三部分組成:
- 已有存款
- 月薪按比例存款;月薪每6個(gè)月有漲幅(這里是重點(diǎn),原文是after 6th month,也就是第7個(gè)月新增變動(dòng)才生效,而不是第6個(gè)月)
- 每月投資回報(bào)
程序代碼
# 起始年薪
# annual_salary = 75000
annual_salary = float(input("Enter your annual salary:"))
# 每月薪資存款比例
# portion_saved = .05
portion_saved = float(input("Enter the percent of your salary to save, as a decimal:"))
# 房?jī)r(jià)
# total_cost = 1500000
total_cost = float(input("Enter the cost of your dream home:"))
# 薪資漲幅
# semi_annual_raise = 0.05
semi_annual_raise = float(input("The semi-annual salary raise:"))
# 首付比例
portion_down_payment = 0.25
# 存款年化率
r = 0.04
# 當(dāng)前存款
current_savings = 0
# 當(dāng)前月份
month_count = 1
# 首付
down_payment = total_cost * portion_down_payment
# while loop
while True:
# 當(dāng)月情況判斷
# 計(jì)算當(dāng)月存款 = 存款 + 月薪*每月薪資存款比例 + 投資回報(bào)
current_savings = current_savings + annual_salary/12*portion_saved + current_savings*r/12
# print("第{}個(gè)月,薪水{},存款{},首付{}".format(month_count, annual_salary, current_savings, down_payment))
if current_savings >= down_payment:
print("Number of months: {}".format(month_count))
break
if month_count % 6 == 0:
annual_salary += annual_salary * semi_annual_raise
# 月份自增
month_count += 1