|  | 
|  | 1 | +# Copyright 2013, Michael H. Goldwasser | 
|  | 2 | +# | 
|  | 3 | +# Developed for use with the book: | 
|  | 4 | +# | 
|  | 5 | +#    Data Structures and Algorithms in Python | 
|  | 6 | +#    Michael T. Goodrich, Roberto Tamassia, and Michael H. Goldwasser | 
|  | 7 | +#    John Wiley & Sons, 2013 | 
|  | 8 | +# | 
|  | 9 | +# This program is free software: you can redistribute it and/or modify | 
|  | 10 | +# it under the terms of the GNU General Public License as published by | 
|  | 11 | +# the Free Software Foundation, either version 3 of the License, or | 
|  | 12 | +# (at your option) any later version. | 
|  | 13 | +# | 
|  | 14 | +# This program is distributed in the hope that it will be useful, | 
|  | 15 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of | 
|  | 16 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the | 
|  | 17 | +# GNU General Public License for more details. | 
|  | 18 | +# | 
|  | 19 | +# You should have received a copy of the GNU General Public License | 
|  | 20 | +# along with this program.  If not, see <http://www.gnu.org/licenses/>. | 
|  | 21 | + | 
|  | 22 | +def prefix_average1(S): | 
|  | 23 | +  """Return list such that, for all j, A[j] equals average of S[0], ..., S[j].""" | 
|  | 24 | +  n = len(S) | 
|  | 25 | +  A = [0] * n                     # create new list of n zeros | 
|  | 26 | +  for j in range(n): | 
|  | 27 | +    total = 0                     # begin computing S[0] + ... + S[j] | 
|  | 28 | +    for i in range(j + 1): | 
|  | 29 | +      total += S[i] | 
|  | 30 | +    A[j] = total / (j+1)          # record the average | 
|  | 31 | +  return A | 
|  | 32 | + | 
|  | 33 | +def prefix_average2(S): | 
|  | 34 | +  """Return list such that, for all j, A[j] equals average of S[0], ..., S[j].""" | 
|  | 35 | +  n = len(S) | 
|  | 36 | +  A = [0] * n                     # create new list of n zeros | 
|  | 37 | +  for j in range(n): | 
|  | 38 | +    A[j] = sum(S[0:j+1]) / (j+1)  # record the average | 
|  | 39 | +  return A | 
|  | 40 | + | 
|  | 41 | +def prefix_average3(S): | 
|  | 42 | +  """Return list such that, for all j, A[j] equals average of S[0], ..., S[j].""" | 
|  | 43 | +  n = len(S) | 
|  | 44 | +  A = [0] * n                   # create new list of n zeros | 
|  | 45 | +  total = 0                     # compute prefix sum as S[0] + S[1] + ... | 
|  | 46 | +  for j in range(n): | 
|  | 47 | +    total += S[j]               # update prefix sum to include S[j] | 
|  | 48 | +    A[j] = total / (j+1)        # compute average based on current sum | 
|  | 49 | +  return A | 
0 commit comments