bisection search
有递归,无递归两种写法
def achieve_down_payment(num, annual_salary, portion_down_payment):
current_savings = 0
month =1
while ((current_savings - portion_down_payment) < (-100)):
portion_saved = num * 0.0001 * annual_salary / 12
if month == 1:
current_savings = portion_saved
else:
current_savings = current_savings * r / 12 + portion_saved + current_savings
if month % 6 == 0:
annual_salary = annual_salary * (1 + semi_annual_raise)
month += 1
return month
def bisection_search(list, left, right, steps):
if left > right:
return -1, steps
if left <= right:
mid = (left + right) // 2
if achieve_down_payment(list[mid], annual_salary, portion_down_payment) > 36:
left = mid+1
steps += 1
elif achieve_down_payment(list[mid], annual_salary, portion_down_payment) < 36:
right = mid-1
steps += 1
else:
return list[mid], steps
return bisection_search(list, left, right, steps)
list = []
for i in range(0,10001):
list.append(i)
annual_salary = int(input('Enter your annual salary:'))
total_cost = 1000000
semi_annual_raise= 0.07
portion_down_payment = 0.25 * total_cost
r = 0.04
left = 0
right = len(list)-1
steps = 1
num, step = bisection_search(list, left, right, steps)
if num == -1:
print('It is not possible to pay the down payment in three years.')
else:
print('Best savings rate:%.4f'%(num*0.0001))
print('Steps in bisection search:',step)
二分查找的时间复杂度 O(logn)
来源:CSDN
作者:松鼠爆米花
链接:https://blog.csdn.net/leonorski/article/details/104703970