Program: Algorithms_1_overdraft.py
#Algorithms and Computational Thinking #Program for Example 1 # # Calculate the penalty without sorting the withdrawals def calculatePenalty1(withdrawals, balance): total = 0 for i in range (len (withdrawals)): total = total + withdrawals[i] if total > balance: break cutoff_notsorted = i penalty = 25 * (len (withdrawals) - cutoff_notsorted) #calculate penalty return penalty #Calculate the penalty after sorting the withdrawals def calculatePenalty2(withdrawals, balance): total = 0 withdrawals.sort() withdrawals.reverse() for i in range (len (withdrawals)): total = total + withdrawals[i] if total > balance: break cutoff_sorted = i penalty = 25 * (len (withdrawals) - i) return penalty #Example data total_balance = 120 withdrawal_list = [2, 7, 15, 5, 80, 25, 10] penalty1 = calculatePenalty1(withdrawal_list, total_balance) penalty2 = calculatePenalty2(withdrawal_list, total_balance) print "Penalty when withdrawals are processed in order of made transactions: ", penalty1 print "Penalty when withdrawals are processed from the largest to the smallest: ", penalty2 if (penalty2 > penalty1): print "Bank profit: ", penalty2-penalty1
Output:
Penalty when withdrawals are processed in order of made transactions: 50 Penalty when withdrawals are processed from the largest to the smallest: 100 Bank profit: 50