【问题标题】:Finding the right amount to save away找到合适的金额来存钱
【发布时间】: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


    【解决方案1】:

    导致迭代次数过多的行是

    portion_saved = max/2.0
    

    你应该这样做

    portion_saved = (max+min)/2.0
    

    因为你正确地做了下面的一些行。

    请注意,您并没有严格遵守分配,因为它要求对 portion_saved 使用 0-10000 范围内的 int 值,而不是 float - 在这个测试用例中,它甚至是一个轻微的优势,因为你获得 11 次迭代而不是 12 次,但在其他情况下可能是相反的。无论如何,如果您想继续使用float,您可以只使用format 结果。

    最后一点非常重要:请不要使用minmax 作为变量名。你覆盖了两个内置函数,所以如果你需要做min(5,2,7),你会得到

    TypeError: 'float' object is not callable
    

    【讨论】:

    • 感谢您的帮助!我还将最小值和最大值编辑为低和高:)
    猜你喜欢
    • 2012-03-26
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-18
    • 1970-01-01
    相关资源
    最近更新 更多