Search code examples
pythonfunctionmathfinance

Function to calculate months required to save for house deposit


Full disclosure this is for an assignment, but I am having some discrepancy between my outputs and the assignment given test cases.

The function takes your annual salary, portion of your salary you'll save per month as a percentage, and the cost of the house.

It's assumed I will need 25% of the total cost of the house. A percentage of my salary goes to my savings each month, I also earn 4% interest per month on my savings.

def house_hunting(annual_salary, portion_saved, total_cost):

    portion_down_payment = 0.25 * total_cost
    current_savings = 0
    r = 0.04
    months = 0

    while current_savings < portion_down_payment:
        current_savings += (annual_salary * portion_saved) / 12
        current_savings += current_savings * r / 12
        months += 1

    return months

print( house_hunting(120000,0.1,1000000) )
print( house_hunting(80000,0.15,500000) )

The first call gives me 182 months, when the test case says 183. The second call gives me 105 months, which is correct according to the test case.

So my math is wrong somewhere; can anyone see where I'm going wrong?


Solution

  • The problem is that you give a month's interest to each new deposit. Instead, you have to wait until the next month. Thus, for each month, you should calculate the interest on the balance held all month, and then make the new deposit. Very simply, switch those two lines:

    while current_savings < portion_down_payment:
        current_savings += current_savings * r / 12
        current_savings += (annual_salary * portion_saved) / 12
        months += 1
    

    Now you get the correct results.