2017-05-25 36 views
0

我目前正在學習Python,這是涉及平分搜索的問題集中的最後一個問題。我覺得我很接近解決這個問題,但不確定我做錯了哪一部分。在36個月內計算房屋首付的儲蓄比例

問題:

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 

如果有人能指出我出錯的地方,那將不勝感激。我想知道如何解決問題,而不是僅僅接收答案。謝謝。

+0

請顯示預期的輸出與實際輸出的內容。你有沒有做過任何調試? – Carcigenicate

+0

你被困在你的while循環中 – thesonyman101

+0

你每6個月增加7%的基礎上150K?我可以有你的工作嗎? ;-) – ShadowRanger

回答

1

您沒有考慮到您的代碼中的semi_annual提高。一些代碼效果如下

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