【发布时间】:2021-05-25 15:45:04
【问题描述】:
我目前正在学习 python,作为一个小测试,我的一个朋友给了我一个来自 MIT 开放课件 python 课程的问题。但是,我正在努力解决问题的 C 部分。如果您想在 3 年内以起薪购买房屋,则需要使用二分搜索来找到您需要节省的合适金额。
这里是问题 pdf 以获取更多详细信息(滚动到 C 部分): https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-programming-in-python-fall-2016/assignments/MIT6_0001F16_ps1.pdf
我已经从技术上“解决”了它,并且能够根据给定的测试用例找到正确的值,但是百分比有很多位数,并且计算的二分搜索量远高于测试用例。
我想知道我的代码是否真的有任何问题,以及我是否针对这个问题正确实施了二进制搜索。
示例测试用例: 测试用例 1:
输入起薪:150000
最佳储蓄率: 0.4411
二分搜索的步骤: 12
我的结果:
输入起薪:150000
最佳储蓄率:0.4411391177390328
二分搜索的步骤: 40
感谢您的帮助!
提前为这个问题道歉,我还在学习;P
我的代码:
annual_salary = float(input('Enter the starting salary: '))
constant = annual_salary
semi_annual_rate = 0.07
r = 0.04
down_payment = 0.25
total_cost = 1000000
current_savings = 0
months = 0
bisection_count = 0
min = 0
max = 1
portion_saved = (max/2.0)/1000
if(annual_salary*3<down_payment*total_cost):
print('It is not possible to pay the down payment in three years.')
while(True):
while(months<36):
current_savings += (current_savings*r/12)+(portion_saved*(annual_salary/12))
months+=1
if(months % 6 == 0):
annual_salary += annual_salary*semi_annual_rate
if(current_savings >= down_payment*total_cost+100):
max = portion_saved
portion_saved = max/2.0
bisection_count+=1
months = 0
current_savings = 0
annual_salary = constant
elif(current_savings >= down_payment*total_cost-100 and current_savings <= down_payment*total_cost+100):
break
else:
min = portion_saved
portion_saved = (max+min)/2.0
bisection_count+=1
months = 0
current_savings = 0
annual_salary = constant
print('Best savings rate: ', portion_saved)
print('Steps in bisection search: ', bisection_count)
【问题讨论】:
标签: python