# Lab 7, CS0007, Fall 2009 # # Files and 2-dimensional arrays # # Precondition for the input files in this module: # The file must also have 3 header lines. # After that, Each line of the # file contains the average monthly temperatures for a year (separated # by spaces) starting with January. # # Make through you trace through your code so you understand the data # structure, and how you are accessing its components! # # So you have practice with them, use nested lists to represent the temperatures. # Each element of the list is a list of 12 measurements, one for each month. # # Then, e.g., temperatures[2][5] is the temperature in the 5th month of the second year. # # Let's use a smaller example: suppose we have only 3 years and 4 months, and the data # is the following: # #24.7 25.7 30.6 47.5 #16.1 19.1 24.2 45.4 #10.4 21.6 37.4 44.7 # # # Your list will be: # [[24.7,25.7,30.6,47.5],[16.1,19.1,24.2,45.4],[10.4,21.6,37.4,44.7]] # # We'll number the years 0 to 2, and the months 0 to 3. # # temperature[2][3] is 44.7, the temperature for year 2, month 3. # # This is like using 2-dimensional arrays in other languages, # an important thing to know. # # There isn't really much code to write! Some functions should # call other functions in the file, and each function can be written # in a few lines. def input_temperature_data(filename): '''Open the specified filename, read past the three-line header, read in the temperature data on the file, and close the file. Return the temperature data in the form of a list of lists, where each list element is a list of 12 temperature readings.''' # Hint: use readline to read the first three lines, and then # a while loop as in files.py to read the numbers # # Hint: you need to convert the strings read from input to float numbers pass def avg_temp_march(temp_data): '''Return the average temperature for the month of March as a float for all years in temp_data. temp_data is the data structure returned by input_temperature_data.''' pass def avg_temp(temp_data, mo): '''Return the average temperature for month mo as a float for all years in temp_data, where mo is an integer between 0 and 11, representing January to December, respectively. temp_data is the data structure returned by input_temperature_data.''' pass def higher_avg_temp(temp_data, mo1, mo2): '''Return either mo1 or mo2 (integers representing months in the range 0 to 11), whichever has the higher average temperature for all years in temp_data. If the months have the same average temperature, then return -1. temp_data is the data structure returned by input_temperature_data.''' pass def avg_temps (temp_data): ''' Return the average of all the temperatures sotred in temp_data. temp_data is the data structure returned by input_temperature_data.''' if __name__ == '__main__': temp_data = input_temperature_data("lab7.dat") print avg_temp_march(temp_data),"sb",32.475 print avg_temp(temp_data,3),"sb",46.525 print higher_avg_temp(temp_data,2,3),"sb",3