逻辑错了吗?计算可节省的薪金百分比,以支付首付

时间:2019-05-17 07:59:05

标签: python python-3.x

问题是使用二等分搜索来查找薪水中要在3年内节省的部分,以支付定金。我的代码无法实现测试用例。我的代码似乎没有问题?

  1. 半年加薪为0.07
  2. 投资的年回报率为0.04
  3. 首付是房屋成本的0.25
  4. 房屋费用为100万美元
  5. 保存期限为36个月
  6. 储蓄在首付$ 100以内

要满足的测试用例:

  1. 测试案例1

    • 起薪:150000
    • 储蓄率:0.4411
    • 采取的步骤:12
  2. 测试案例2

    • 起薪:300000
    • 储蓄率:0.2206
    • 已采取的步骤:9
  3. 测试案例3

    • 起薪:10000
    • 无法在三年内支付首付款

我得到的结果如下

  1. 测试案例1

    • 起薪:150000
    • 储蓄率:0.1295
    • 采取的步骤:13
  2. 测试案例2

    • 起薪:300000
    • 储蓄率:0.0647
    • 采取的步骤:14
  3. 测试案例3

    • 起薪:10000
    • 无法在三年内支付首付款
annual_salary = int(input("Enter your annual salary: "))
the_annual_salary = annual_salary
total_cost = 1000000
semi_annual_raise = 0.07
portion_down_payment = 0.25
r = 0.04
num_months = 36
num_steps = 0

high = 10000
low = 0
guess = (high+low) / 2
current_savings = 0

while abs(current_savings - (portion_down_payment * total_cost)) > 100:
    current_savings = 0
    annual_salary = the_annual_salary
    for i in range(num_months):
        current_savings +=  current_savings * r/12
        current_savings += annual_salary * (guess/10000) /12
        if num_months % 6 == 0:
            annual_salary += semi_annual_raise * annual_salary

    if current_savings < portion_down_payment * total_cost:
        low = guess
        if guess == 10000:
            break

    elif current_savings > portion_down_payment * total_cost:
        high = guess        

    num_steps += 1
    guess = (high+low) / 2       


if (guess == 10000) and (current_savings < portion_down_payment * total_cost + 100):
    print("It is not possible to pay for the down payment in 36 months")
else:
    print("Percent of salary to save is", guess/10000)
    print("Number of steps taken:", num_steps)

1 个答案:

答案 0 :(得分:0)

哦,我发现了问题... =。=

在if语句中,应将i替换为num_months,因为i是循环中使用的临时变量。

for i in range(num_months):
    current_savings +=  current_savings * r/12
    current_savings += annual_salary * (guess/10000) /12
    if i % 6 == 0:
        annual_salary += semi_annual_raise * annual_salary

获得的结果

  1. 测试案例1

    • 起薪:150000
    • 储蓄率:0.4169
    • 采取的步骤:12
  2. 测试案例2

    • 起薪:300000
    • 储蓄率:0.2084
    • 采取的步骤:13
  3. 测试案例3

    • 起薪:10000
    • 无法在三年内支付首付款