Wednesday, May 21, 2008

Google Treasure Hunt - Sums of files

A Python solution program for the Google Treasure Hunt question: Product of sums of particular lines in files with names matching certain conditions.
You can download the program here. Remove the ".txt" from the ending of the file.

# Solution for Google Treasure Hunt Question below:
# http://treasurehunt.appspot.com/ (sum of lines in files)
# Place this file in the folder where you downloaded and
# unzipped the google zip file containing the files. Set
# the UNZIPPED_FOLDER_NAME and other params below and run
# it from the command line

# Author: Pramod Biligiri, pramodbiligiri at gmail,
# http://pramodbiligiri.blogspot.com
from os import path

# Start of config vars
#Enter the name of the folder created when you unzip the download
#I suggest you rename the long random name to "google"
UNZIPPED_FOLDER_NAME = "google"

# For both files, enter the file extensions, the part of filename
# to look for, and the line number whose sum is to be added
EXT1, EXT2 = ".xml", ".rtf"
SEARCH_STRING1, SEARCH_STRING2 = "jkl", "vwx"
LINE1, LINE2 = 4, 5
# End of config vars

def addvalue(filename, result):
lines = [it.strip() for it in file(filename).readlines()]

if(filename.endswith(EXT1) and len(lines) >= LINE1):
result[0] += int(lines[LINE1-1])
if(filename.endswith(EXT2) and len(lines) >= LINE2):
result[1] += int(lines[LINE2-1])


def count(result, dirname, fnames):
for fname in fnames:
full = dirname + "\\" + fname
fullstr = "".join(full.split("\\"))[len(UNZIPPED_FOLDER_NAME):]
if not path.isdir(full):
if ((SEARCH_STRING1 in fullstr) and (fname.endswith(EXT1)) or ((SEARCH_STRING2 in fullstr) and (fname.endswith(EXT2)))):
addvalue(full, result)

def main():
result = [0,0]
path.walk(UNZIPPED_FOLDER_NAME, count, result)
print reduce(lambda x,y: x*y, result, 1)

if __name__ == "__main__":
main()