# file: change.py # author: Bob Muller # # CS1101 Computer Science I # # Code implementing a greedy algorithm for making change. The # algorithm returns the smallest list of coins adding up to a # given amount. NB: this algorithm only works for certain sets # of coins, including US coinage. # getLargest : int list -> (int * int list) # # The call getLargest(coins) returns a pair (c, coins') where # c is the largest coin in coins and coins' are the leftovers. # def getLargest(coins): big = max(coins) return (big, [ coin for coin in coins if coin <> big ]) # change : int * int list -> int list # # The call change(amount, coins) returns the fewest coins drawn # from the list that add up to amount. # def change(amount, coins): if amount == 0: return [] else: (largestCoin, otherCoins) = getLargest(coins) numLargest = amount / largestCoin residualAmount = amount % largestCoin return ([largestCoin] * numLargest) + change(residualAmount, otherCoins)