# Read a two-dimensional array from a file, then # compute the weighted average of the first column # using the weights in the second column. # Use two methods read_2d_array and weighted_ave. # Define method to read values of two-dimensional # array from an input file. Fields beyond 0 and 1 # are ignormed. def read_2d_array(the_filename): data = [ ] f = open(the_filename, "r") line = f.readline( ) while line: fields = line.split(",") value = float(fields[0].strip( )) weight = float(fields[1].strip( )) data.append([value, weight]) line = f.readline( ) return data # Define method to compute weighted average of # values in a data matrix. The values are in # column 0 and the weights are in column 1. # Here is the formula for the weighted average: # weighted_ave = # (sum of value * weight) / (sum of weights) def weighted_ave(the_data_array): sum_weighted_values = 0.0 sum_weights = 0.0 for row in the_data_array: sum_weighted_values += row[0] * row[1] sum_weights += row[1] return sum_weighted_values / sum_weights # Use methods to compute weighted average # of values in file data = read_2d_array("course-scores.txt") print("Course Score: {0:.2f}".format(weighted_ave(data)))