计算36个月内房屋预付款的储蓄百分比

时间:2017-05-25 01:22:16

标签: python python-3.x bisection

我目前正在学习Python,这是涉及二分搜索的问题集中的最后一个问题。我觉得我非常接近解决这个问题,但不确定我做错了哪一部分。

问题:

Write a program to calculate the savings percentage you need each month to afford
the down payment in three years (36 months).
Down payment: $250000
Semi-annual raise: 0.07 (7% raise every 6 months)
Investment return: 0.04 (4%)

代码:

salary = 150000
semi_annual_raise = 0.07
investment_return = 0.04
down_payment = 250000

low = 0
high = 10000
percent_saved = int((low + high)/2)
current_savings = 0.0
steps = 0
months = 0    

print('Annual salary:', salary)

while current_savings < down_payment:
    percent_saved = percent_saved/10000
    monthly_salary = salary/12
    current_savings += current_savings*investment_return/12
    current_savings += monthly_salary*percent_saved

    if current_savings < down_payment:
        low = percent_saved
    elif current_savings > down_payment:
        high = percent_saved
        print('Best savings rate:', percent_saved)
        print('Steps in bisection search:', steps)
        break
    else:
        print('It is not possible to pay the down payment in three years.')
        break
    percent_saved = (low + high)/2
    steps += 1
    months += 1

我的输出:

Annual salary: 150000
Best savings rate: 0.5000250012500626
Steps in bisection search: 39

测试用例(正确输出):

Annual salary: 150000
Best savings rate: 0.4411
Steps in bisection search: 12

如果有人能够指出我出错的地方,我将不胜感激。我想知道如何解决问题而不是仅仅接收答案。谢谢。

1 个答案:

答案 0 :(得分:1)

您没有考虑代码中的半年加薪。一些代码的效果

months = 1.0
c_raise = 0.0
year3income = 0.0
while months <=36:
    if months%6 ==0:
        c_raise +=1
        monthly_salary += monthly_salary*semi_annual_raise
    year3income +=monthly_salary+monthly_salary*yearly_return
    months+=1