Commits

John Chandler committed 68d655f

Refactored parts 1 and 2: pulled duplicate code out into common.py

  • Participants
  • Parent commits 4ef0cd4

Comments (0)

Files changed (3)

File kata4/common.py

+"""
+http://codekata.pragprog.com/2007/01/kata_four_data_.html
+
+This module contains code extracted from both part1.py and part2.py that can be used in the refactored versions
+
+"""
+
+def parse_file( filename, extraction_function ):
+    """ Parses a weather.dat format file """
+    data_file = open( filename, "r" )
+
+    data = []
+    for line in data_file:
+        extracted_data = extraction_function( line )
+        if extracted_data:
+            data.append( extracted_data )
+
+    return data
+
+
+def get_item_with_smallest_difference( data, label_index, value1_index, value2_index ):
+    """ Takes a list (data) of lists.
+        Returns the 'label' of a row where the difference between two integer items in the row is the smallest out of all rows
+    """
+
+    smallest_label = None
+    smallest_diff  = None
+
+    for row in data:
+        diff = abs( int(row[value1_index]) - int(row[value2_index]) )
+        if smallest_diff > diff or smallest_diff is None:
+            smallest_label = row[label_index]
+            smallest_diff  = diff
+
+    return smallest_label
+
+

File kata4/part1_refactored.py

+"""
+http://codekata.pragprog.com/2007/01/kata_four_data_.html
+"""
+
+import re
+
+from common import parse_file, get_item_with_smallest_difference
+
+
+DATA_LINE_RE = re.compile( "^\s+(\d+)\s+(\d+)\s+(\d+)\s" )
+
+DAY      = 0
+MAX_TEMP = 1
+MIN_TEMP = 2
+
+
+def extract_weather_record( line ):
+    """ Returns a (dy, mxt, mnt) tuple if a vaid weather record
+        Returns None if not
+    """
+    match = DATA_LINE_RE.match( line )
+    if match:
+        dy  = int(match.group(1))
+        mxt = int(match.group(2))
+        mnt = int(match.group(3))
+
+        return ( dy, mxt, mnt )
+
+    return None
+
+
+if __name__ == "__main__":
+    data = parse_file( "weather.dat", extract_weather_record )
+    
+    print get_item_with_smallest_difference( data, DAY, MAX_TEMP, MIN_TEMP )

File kata4/part2_refactored.py

+"""
+http://codekata.pragprog.com/2007/01/kata_four_data_.html
+"""
+
+import re
+
+from common import parse_file, get_item_with_smallest_difference
+
+
+WHITESPACE_RE = re.compile( "\s+" )
+
+TEAM_NAME     = 2
+GOALS_FOR     = 7
+GOALS_AGAINST = 9
+
+
+def extract_football_record( line ):
+    """ Extracts a tuple of fields if a valid football data record
+        Returns None if not
+    """
+    columns = WHITESPACE_RE.split( line )
+    if len( columns ) == 12:
+        return columns
+    return None
+
+
+if __name__ == "__main__":
+    data = parse_file( "football.dat", extract_football_record )
+    
+    print get_item_with_smallest_difference( data, TEAM_NAME, GOALS_FOR, GOALS_AGAINST )