# # This file shows an answer to the opening exercise, total_margin, # and then evolves that code into a functional solution. # games = [ [102, 51], [78, 67], [53, 94], [64, 75], [54, 71], [64, 68] ] # imperative solution total_margin = 0 for p in games: difference = abs(p[0]-p[1]) total_margin += difference # examine the loop total_margin = 0 for p in games: difference = abs(p[0]-p[1]) # 1. do something with p total_margin += difference # 2. accumulate result from #1 # separate this into two loops # --------------------------------------------------------------- # in loop 1, change "do something with result" to *record* result results = [] for p in games: difference = abs(p[0]-p[1]) # 1. do something with p results.append(difference) # 2. record result from #1 # then factor "do something with p" into a function def margin_for(two_list): return abs(two_list[0]-two_list[1]) # and use the function results = [] for p in games: difference = margin_for(p) # 1. do something with p -- in a fxn results.append(difference) # 2. record result from #1 # map does all of this... just give it margin_for() results = map(margin_for, games) # map produces a "map object" that we can loop over # --------------------------------------------------------------- # now, the second loop adds up the results total_margin = 0 for r in results: total_margin += r # 1. accumulate result from #1 # Python 3 doesn't have a generic reduce function. # In this case, we can sum a list made from the map: # # total_margin = sum(list(results)) # -------------------------------------------------------------- # in Racket, apply does all of this -- as long as you give it +: # # (apply + results)