gpt4 book ai didi

python - 计算36个月内首付的储蓄百分比

转载 作者:太空宇宙 更新时间:2023-11-03 15:11:39 25 4
gpt4 key购买 nike

我目前正在自学 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

如果有人能指出我错在哪里,我将不胜感激。我想知道如何解决问题,而不是仅仅得到答案。谢谢。

最佳答案

您没有在代码中考虑 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

关于python - 计算36个月内首付的储蓄百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44170862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com