- PAYING THE MINIMUM
计算每月信用卡最低还款额及剩余应还款额1 balance = 4842 #还款额 2 annualInterestRate = 0.2 #年利息比率 3 monthlyPaymentRate = 0.04 #每月最低还款比率 4 total = 0 5 #循环计算1-12月 6 for month in range(1, 13): 7 payment = monthlyPaymentRate * balance 8 total += payment 9 balance = (balance - payment) * (1 + annualInterestRate / 12.0) 10 print "Month:", month 11 #round(x,2)保留x两位小数 12 print "Minimum monthly payment:", round(payment, 2) 13 print "Remaining balance:", round(balance, 2) 14 15 print "Total paid:", round(total, 2) 16 print "Remaining balance:", round(balance, 2)
- PAYING DEBT OFF IN A YEAR
保持最低还款时查找一年最低的利息1 balance = 3926 #还款额 2 annualInterestRate = 0.2 #年利息率 3 payment = 0 4 b = 1 5 6 while b > 0: 7 payment += 10 8 b = balance 9 10 for month in range(1, 13): 11 b = (b - payment) * (1 + annualInterestRate / 12.0) 12 13 print "Lowest Payment:", payment
- USING BISECTION SEARCH TO MAKE THE PROGRAM FASTER
使用二分法优化上个问题的实现效率1 balance = 999999 2 annualInterestRate = 0.18 3 4 low = balance / 12.0 5 high = (balance * (1 + annualInterestRate / 12.0)**12) / 12.0 6 7 payment = (high + low) / 2.0 8 b = balance 9 for month in range(1, 13): 10 b = (b - payment) * (1 + annualInterestRate / 12.0) 11 12 while abs(b) > 0.01: 13 if b < 0: 14 high = payment 15 else: 16 low = payment 17 18 payment = (high + low) / 2.0 19 b = balance 20 for month in range(1, 13): 21 b = (b - payment) * (1 + annualInterestRate / 12.0) 22 23 print "Lowest Payment:", round(payment, 2)