我正在努力学习如何使用对分搜索来提高我编写的程序的速度。 但事实证明我失败得很惨。我已经被困了3个小时了,一直在检查我的代码,尝试不同的东西,谷歌搜索,阅读,但仍然一无所获。 所以我来到这里,希望这里的人能帮助我理解为什么我的代码会被破坏,以及我应该如何考虑不再处于这种情况。你知道吗
我尽可能使用print语句来查看我的输出。我看到的是,它只是重复打印相同的数字(猜测),而没有改变它。我想可能是因为一些变量的作用域不在范围内(不能改变?)那可能是我的问题?你知道吗
代码如下:
def evaluatePayment(balance, guess, annualInterestRate):
annualInterestRate = annualInterestRate
balance = balance
minPay = guess
for month in range(1,13):
remainingBalance = balance - minPay
balance = (remainingBalance + remainingBalance * annualInterestRate / 12.0)
#print "month: " + str(month) + " balance: " + str(balance) + " minPay: " + str(minPay)
if balance <= 0:
return balance
else:
return balance
annualInterestRate = 0.2
balance = 320000
monthInt = annualInterestRate / 12.0
upper= evaluatePayment(balance, 0, annualInterestRate)/12
lower = balance / 12.0
guess = (lower+upper)/2
while True:
if (evaluatePayment(balance, guess, annualInterestRate)) <= 0.00 and (evaluatePayment(balance, guess, annualInterestRate)) > -0.13:
print "Lowest Payment: " + str(guess) + " balance: " + str((evaluatePayment(balance, guess, annualInterestRate)))
break
elif (evaluatePayment(balance, guess, annualInterestRate)) > 0.00:
upper = guess
guess = (lower+upper)/2
print str(guess)
elif (evaluatePayment(balance, guess, annualInterestRate)) < 0.00:
lower = guess
guess = (lower+upper)/2
print str(guess)
编辑: 固定压痕。看起来和我的档案不一样。我没有正确粘贴代码。你知道吗
我在@Prerak Sola的帮助下解决了这个问题,并通过纸上的复习解决了这个问题。试着用手解决一次,一切都有意义:D
下面是更新后的代码:
相关问题 更多 >
编程相关推荐