MIT 6.0001 ps1 c

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值