【发布时间】:2018-10-31 17:43:16
【问题描述】:
您好,我需要一些帮助来解决这个设置为 MIT OCW 计算机科学和 Python 课程的问题之一的问题。我知道有人问过类似的问题,我也找到了有用的帖子,例如 Bisection search code doesnt work,但我仍然卡住了!
我已经为这个问题苦苦挣扎了很多天,并试图以不同的方式解决它,但都失败了。如果可能的话,有人可以暗示我哪里出错了,而不是告诉我答案。我想通过一些帮助自己解决这个问题。
由于我一直在努力,我已将这项任务分解为一个总体目标,然后分解为解决问题的步骤。
目标:尝试找到在 36 个月内支付 100 万美元房屋首付的最佳储蓄率##解决问题的步骤:
1) 猜测储蓄率,即 0 和 1000 的平均值
2) 计算 36 个月后的增长情况
3a) 如果在 36 个月内达到的金额超过 100 万美元的 25%,那么较低的储蓄率应该是新的猜测
...max=guess(旧猜测)和 min=0 并更新猜测(高低的平均值)
...使用新的猜测运行步骤 2 中的计算
3b) 如果金额在 36 个月内没有达到 100 万美元的 25%,那么更高的储蓄率应该是新的猜测
...min=guess(旧猜测)并更新猜测(高低的平均值)
...使用新的猜测运行步骤 2 中的计算
3c) 如果金额在第 36 个月期限内达到 100 万美元的 25%,则退出并记录储蓄率作为最佳猜测。
为简单起见:假设没有利息并假设工资保持不变
所以这是我目前正在努力解决这个问题的代码。 (它导致“猜测”变量趋于 0,然后无限循环)
total_cost=1000000 #cost of house
portion_down_payment=0.25 #fraction of cost needed for downpayment on house
downpayment=total_cost*portion_down_payment
starting_annual_salary=float(input("Enter the starting salary: "))
low=0
high=1000
bisect_steps=0
month=1 #set as 1 because the first calculation will occur in month 1
guess=(low+high)//2
current_savings=0
def calSavings(current_savings,monthly_salary,guess,month):
while month<37:
monthly_savings=monthly_salary*(guess/1000)
current_savings+=monthly_savings
month+=1
return(current_savings)
current_savings=calSavings(current_savings,monthly_salary,guess,1)
while True:
current_savings=calSavings(current_savings,monthly_salary,guess,1)
if current_savings>downpayment and month<=35: #if amount reached goes over 25% of $1m within 36 months
#a lower savings rate should be the new guess
high=guess #max=guess (old guess) and min=0 and update the guess
bisect_steps+=1
guess=(low+high)//2
print("The guess was too high, so the new lower guess is",guess," This is bisect step",bisect_steps)
continue #send new guess up to beginning of while loop to calculate
elif current_savings<downpayment and month>=36: #if amount does not reach 25% of $1m within 36 months
low=guess
bisect_steps=+1
guess=(low+high)//2
print("The guess was too low, so the new higher guess is",guess," This is bisect step",bisect_steps)
continue #send new guess up to beginning of while loop to calculate
elif current_savings>=downpayment and month==36: #if amount reaches 25% of $1m in the 36th months then quit
# record the savings rate as the best guess
print("The best savings rate is ",guess/100,"%, the amount saved was ",current_savings," in ",month," months")
break #break out of while loop
我知道其他人也问过类似的问题(我已经查看了这些答案,但仍然没有解决我的问题),但不仅仅是一个答案,我需要关于如何解决这个问题的帮助。
【问题讨论】:
标签: python search binary-search bisection