我试图学习如何使用二分搜索来提高我编写的程序的速度。 但事实证明我惨遭失败。我已经被困了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)
编辑: 固定缩进。它与我的档案看起来并不相同。我没有以正确的方式粘贴代码。
答案 0 :(得分:2)
我在@Prerak Sola的帮助下解决了这个问题并通过纸张解决问题。试图用手一次解决它,一切都有意义:D
所以这里有更新的代码:
"""
This function evaluates the guess to see if it'll solve the problem.
It returns the balance so that you can use it.
"""
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
#Defines the variables needed for this to work
annualInterestRate = 0.18
balance = 999999
monthInt = annualInterestRate / 12.0
upper= evaluatePayment(balance, 0, annualInterestRate)/12
lower = balance / 12.0
guess = (lower+upper)/2
"""
This is where the "guessing" takes part. It will iterate untill it finds a solution.
It takes the original guess and tries it, if it returns false it will check if the
guess was to high or to low and try assign new values depending on the elif-statement.
"""
while True:
if (evaluatePayment(balance, guess, annualInterestRate)) <= 0.00 and (evaluatePayment(balance, guess, annualInterestRate)) > -0.01:
print "Lowest Payment: " + str(round(guess,2)) + " balance: "
break
elif (evaluatePayment(balance, guess, annualInterestRate)) > 0.00:
lower = guess
upper = upper
guess = (lower+upper)/2
#print "high " + str(guess)
elif (evaluatePayment(balance, guess, annualInterestRate)) < 0.00:
upper = guess
lower = lower
guess = (lower+upper)/2
#print "low " + str(guess)