try: #open the file and read in the data #at the end, rowCount and colCount #will contain the number of rows and columns gridValues = [] rowCount = 0 data = open("Problem_00011.data.txt") line = data.readline() while line: values = line.split() colCount = 0 #add a new row to the grid gridValues.append([]) for value in values: #append the value to the current row gridValues[rowCount].append(int(value)) colCount += 1 rowCount += 1 line = data.readline() finally: data.close() maxProduct = 0 #Number of adjacent values to check numAdjacents = 4 i = 0 j = 0 while i < rowCount: j = 0 while j < colCount: product = 0 #check vertical product if i <= rowCount - numAdjacents: product = 1 k = 0 productFactors = [] while k < numAdjacents: product *= gridValues[i + k][j] productFactors.append(gridValues[i + k][j]) k += 1 if product > maxProduct: maxProduct = product maxProductInfo = "The max product is found at %d,%d with the numbers %s in the vertical down direction." % (i,j,productFactors) #check horizontal product if j <= colCount - numAdjacents: product = 1 k = 0 productFactors = [] while k < numAdjacents: product *= gridValues[i][j+k] productFactors.append(gridValues[i][j+k]) k += 1 if product > maxProduct: maxProduct = product maxProductInfo = "The max product is found at %d,%d with the numbers %s in the horizontal right direction." % (i,j,productFactors) #check down-right diagonal if i <= rowCount - numAdjacents and j <= colCount - numAdjacents: product = 1 k = 0 productFactors = [] while k < numAdjacents: product *= gridValues[i+k][j+k] productFactors.append(gridValues[i+k][j+k]) k += 1 if product > maxProduct: maxProduct = product maxProductInfo = "The max product is found at %d,%d with the numbers %s in the down right diagonal direction." % (i,j,productFactors) #check down-left diagonal if i <= rowCount - numAdjacents and j >= numAdjacents - 1: product = 1 k = 0 productFactors = [] while k < numAdjacents: product *= gridValues[i+k][j-k] productFactors.append(gridValues[i+k][j-k]) k += 1 if product > maxProduct: maxProduct = product maxProductInfo = "The max product is found at %d,%d with the numbers %s in the down left diagonal direction." % (i,j,productFactors) j += 1 i += 1 print "The largest product of %d adjacent numbers is %d" % (numAdjacents,maxProduct) print maxProductInfo