-->

Calculate savings percentage for house down paymen

2019-05-31 13:27发布

问题:

I'm currently learning Python on my own and this is the last problem in a problem set involving bisection search. I feel like I'm very close to solving this but not sure which part I did wrong.

Problem:

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%)

Code:

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

My output:

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

Test Case (Correct output):

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

If someone can point out where I went wrong that would be greatly appreciated. I want to know how to solve the problem instead of just receiving the answer. Thank you.

回答1:

You didn't account for the semi_annual raise in your code. Some code to the effect of

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