MIT 6.0001 ps1 c

十年热恋 提交于 2020-03-07 04:32:46

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)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!