CSC111 Homework 13 Solution Program 2014

From dftwiki3
Revision as of 16:59, 5 May 2014 by Thiebaut (talk | contribs) (Created page with "--~~~~ ---- <source lang="python"> # hw13a.py # D. Thiebaut # This program reads several text files formatted in CSV format. # Each file represents temperatures and rain fall ...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

--D. Thiebaut (talk) 16:59, 5 May 2014 (EDT)


# hw13a.py
# D. Thiebaut
# This program reads several text files formatted in CSV format.
# Each file represents temperatures and rain fall data recorded
# for a specific city in the UK.  The array temp below contains
# all the city names and their associated file names.
#
# The program prompts the user for a year and month and outputs
# the city that experienced the largest rain fall that period.
#
# Then the program outputs the city which recorded the largest
# difference between mean and max temperature in the year 2000
# or later.
#
# The final output is a list of all the cities sorted by year
# when a temperature recording was made for each.  The list is
# sorted by year.

temp = [ ('Aberporth', 'aberporthdata.txt'),
         ('Armagh', 'armaghdata.txt'),
         ('Ballypatrick Forest', 'ballypatrickdata.txt'),
         ('Bradford', 'bradforddata.txt'),
         ('Braemar', 'braemardata.txt'),
         ('Camborne', 'cambornedata.txt'),
         ('Cambridge NIAB', 'cambridgedata.txt'),
         ('Cardiff Bute Park', 'cardiffdata.txt'),
         ('Chivenor', 'chivenordata.txt'),
         ('Cwmystwyth', 'cwmystwythdata.txt'),
         ('Dunstaffnage', 'dunstaffnagedata.txt'),
         ('Durham', 'durhamdata.txt'),
         ('Eastbourne', 'eastbournedata.txt'),
         ('Eskdalemuir', 'eskdalemuirdata.txt'),
         ('Heathrow', 'heathrowdata.txt'),
         ('Hurn', 'hurndata.txt'),
         ('Lerwick', 'lerwickdata.txt'),
         ('Leuchars', 'leucharsdata.txt'),
         ('Lowestoft',  'lowestoftdata.txt'),
         ('Manston', 'manstondata.txt'),
         ('Nairn', 'nairndata.txt'),
         ('Newton Rigg',  'newtonriggdata.txt'),
         ('Oxford', 'oxforddata.txt'),
         ('Paisley', 'paisleydata.txt'),
         ('Ringway', 'ringwaydata.txt'),
         ('Ross-on-Wye', 'rossonwyedata.txt'),
         ('Shawbury', 'shawburydata.txt'),
         ('Sheffield', 'sheffielddata.txt'),
         ('Southampton', 'southamptondata.txt'),
         ('Stornoway Airport',  'stornowaydata.txt'),
         ('Sutton Bonington', 'suttonboningtondata.txt'),
         ('Tiree', 'tireedata.txt'),
         ('Valley',  'valleydata.txt'),
         ('Waddington', 'waddingtondata.txt'),
         ('Whitby', 'whitbydata.txt'),
         ('Wick Airport',  'wickairportdata.txt'),
         ('Yeovilton', 'yeoviltondata.txt') ]


# getStats: reads the files and return 3 different dictionaries
# containing the data in various forms:
# fileNameOf: returns the file name associated with a given city
# nameOfFile: returns the city name associated with a given file
# linesOf: returns the list of lines of text associated with a given
#          city
def getStats():
    # init the dictionaries
    fileNameOf = {}
    nameOfFile = {}
    linesOf    = {}
    
    # go through each file and record the data of interest
    for i,pair in enumerate( temp ):
        name = pair[0]
        fileName = pair[1]

        # update the dictionaries
        fileNameOf[name] = fileName
        nameOfFile[fileName] = name
        file = open( fileName, 'r' )
        linesOf[ name] = file.readlines()
        file.close()

    return linesOf, nameOfFile, fileNameOf

# The main program does all the work.   
def main():
    linesOf, nameOfFile, fileNameOf = getStats()

    # get the year and month from the user (or constants)
    wantedYear = 2011 #int( input( "please enter year: " ) )
    wantedMonth = 11  #int( input( "please enter month: " ) )

    # initializes 
    dico  = {}    # dictionary used to keep track of whether a
                  # year has been recorded for a given city,
    list1 = []    # used to keep rain-fall data
    list2 = []    # used to keep temperature differences
    list3 = []    # used to record year of temp. recorded and cities

    # go through each city
    for i,(name, fileName) in enumerate( temp ):
        
        # get the contents of the file from the dictionary
        lines = linesOf[ name ]

        # go through each line of the file
        for line in lines:

            # clean it up
            line = line.strip().replace( '*', '' )

            # does it start with a year?            
            if line[0:2] in [ "17", "18", "19", "20" ]:

                # extract what we're after
                words = line.split()
                year = int( words[0] )
                month= int( words[1] )

                # see if we can get the rain-fall data
                try:
                    if year==wantedYear and month==wantedMonth:
                        rain = float( words[5] )
                        list1.append( (rain, name ) )

                except:
                    pass

                # see if we can compute the difference in max/min temperatures                    
                try:                
                    diff = float( words[2]) - float( words[3] )

                    # if we're here, the temperatures are valid
                    if name not in dico:
                        # if this is the first time we're seeing a temperature
                        # for this city, record it
                        dico[name] = year
                        list3.append( (name, year) )                    

                    # if the year is 2000 or over, record the difference 
                    if year >= 2000:
                        list2.append( (diff, name, month, year) )
                except:
                    pass
                

    # output abbreviated answer to Question 1    
    list1.sort()
    list1.reverse()
    print( "max rain found in %s, with %d mm" %
           ( list1[0][1], list1[0][0] ) )

    # output abbreviated answer to Question 2
    list2.sort()
    list2.reverse()
    print( "max diff found in %s with %1.3f difference temp (%d %d)" %
           ( list2[0][1], list2[0][0], list2[0][2], list2[0][3] ) )
    for i in range( 1, len( list2 ) ):
        if list2[i][0]==list2[0][0]:
            print( "max diff found in %s with %1.3f difference temp (%d %d)" %
               ( list2[i][1], list2[i][0], list2[i][2], list2[i][3] ) )
        else:
            break

    # output abbreviated answer to Question 3
    list3 = [ (year, name) for name, year in list3 ]
    list3.sort()
    for name, year in list3:
        print( "%4d %s" % (name, year ) )
        
        
    

main()