Source

metaljoe_codekata / kata4 / part1.py

"""
http://codekata.pragprog.com/2007/01/kata_four_data_.html

In weather.dat you'll find daily weather data for Morristown, NJ for June 2002. Download this text file, then write a program to output the day number (column one) with the smallest temperature spread (the maximum temperature is the second column, the minimum the third column). 
"""

import re

DATA_LINE_RE = re.compile( "^\s+(\d+)\s+(\d+)\s+(\d+)\s" )


def parse_file( filename ):
    """ Parses a weather.dat format file """
    data_file = open( filename, "r" )

    data = []
    for line in data_file:
        match = DATA_LINE_RE.match( line )
        if match:
            dy  = int(match.group(1))
            mxt = int(match.group(2))
            mnt = int(match.group(3))

            data.append( (dy, mxt, mnt) )

    return data


def print_day_with_smallest_spread( data ):
    """ Prints day with the lowest spread """
    smallest_day    = None
    smallest_spread = None

    for dy, mxt, mnt in data:
        spread = mxt - mnt
        if smallest_spread > spread or smallest_spread is None:
            smallest_day = dy
            smallest_spread = spread

    print smallest_day



if __name__ == "__main__":
    data = parse_file( "weather.dat" )
    
    print_day_with_smallest_spread( data )