【发布时间】:2020-05-18 07:10:49
【问题描述】:
我遇到了一个 MIT 开源 Python 编码实践
假设您希望能够在三年内支付首付。你每个月应该存多少钱来实现这个目标?在这个问题中,你将编写一个程序来回答这个问题。为简化起见,假设:
1.您的半年加薪为 0.07 (7%)
2.您的投资的年回报率为 0.04 (4%)
3. 首付是房屋成本的 0.25 (25%)。
4.您节省的是 100 万美元。您现在将尝试找到最佳的储蓄率,以在 36 个月内支付 100 万美元的房屋首付。由于要做到这一点是一项挑战,我们只希望您的储蓄在所需首付的 100 美元以内。编写一个程序来计算最佳储蓄率,作为您起薪的函数。您应该使用 [bisection search] 来帮助您有效地执行此操作。您应该跟踪完成二等分搜索所需的步骤数。将浮点数限制为小数点后两位(即,我们可能希望保存为 7.04% - 或十进制的 0.0704 - 但我们不会担心 7.041% 和 7.039% 之间的增量)。这意味着我们可以搜索 0 到 10000 之间的整数(使用整数除法),然后将其转换为小数百分比(使用浮点除法),以便我们在 36 个月后计算 current_savings 时使用。使用这个范围只会给我们提供我们正在搜索的有限数量的数字,而不是 0 和 1 之间的无限小数。这个范围将有助于防止无限循环。我们使用 0 到 10000 的原因是为了在 0% 到 100% 的范围内增加两个小数位。您的代码应打印出小数点(例如 0.0704 表示 7.04%)。 请记住,有些工资可能无法在一年半内节省首付。在这种情况下,您的函数应通过打印声明通知用户无法在 36 个月内保存首付。
示例输出
输入起薪:150000
最佳储蓄率:0.4411
二分搜索步骤:12
以下是我找到的解决方案之一。
# user input
annual_salary = float(input('Enter your annual salary: '))
# static variables and initializers
semi_annual_raise = 0.07
r = 0.04
portion_down_payment = 0.25
total_cost = 1000000
steps = 0
current_savings = 0
low = 0
high = 10000
guess_rate = (high + low)//2
# Use a while loop since we check UNTIL something happens.
while abs(current_savings - total_cost*portion_down_payment) >= 100:
# Reset current_savings at the beginning of the loop
current_savings = 0
# Create a new variable for use within the for loop.
for_annual_salary = annual_salary
# convert guess_rate into a float
rate = guess_rate/10000
# Since we have a finite number of months, use a for loop to calculate
# amount saved in that time.
for month in range(36):
# With indexing starting a zero, we need to calculate at the beginning
# of the loop.
if month % 6 == 0 and month > 0:
for_annual_salary += for_annual_salary*semi_annual_raise
# Set monthly_salary inside loop where annual_salary is modified
monthly_salary = for_annual_salary/12
# Calculate current savings
current_savings += monthly_salary*rate+current_savings*r/12
# The statement that makes this a bisection search
if current_savings < total_cost*portion_down_payment:
low = guess_rate
else:
high = guess_rate
guess_rate = (high + low)//2
steps += 1
# The max amount of guesses needed is log base 2 of 10000 which is slightly
# above 13. Once it gets to the 14th guess it breaks out of the while loop.
if steps > 13:
break
# output
if steps > 13:
print('It is not possible to pay the down payment in three years.')
else:
print('Best savings rate:', rate)
print('Steps in bisection search:', steps)
为什么需要在 FOR 循环之前重置变量值 current_savings 并创建一个 for_annual_salary? current_savings一开始就已经定义为0了,为什么在FOR循环中没有使用annual_salary,而是创建了一个全新的变量for_annual_salary?
【问题讨论】:
-
如果没有创建其他变量并且必须修复它,那么年薪水将在 for 循环内发生变化,电流储蓄也是如此,但在这种情况下,我们只需要设置它在每次迭代时为 0。
标签: python python-3.x python-3.6 python-3.5