Now that I've though about it, there must be a better way of reading data into a Python list. And there is! I copy the data into a textfile and then read the textfile.
lines = [] with open('pe11.txt') as file: for line in file: lines = file.read().splitlines()
This is not enough though, I want a two dimensional matrix. I need to know how to add space separated values from a textfile to a Python list.
with open('pe11.txt', 'r') as file: lines = [[int(num) for num in line.split()] for line in file] product = 1rowProduct = 1colProduct = 1diaDownProduct = 1diaUpProduct = 1 for row in range(0, 20): for col in range(0, 17): newProduct = lines[row][col] * lines[row][col + 1] * lines[row][col + 2] * lines[row][col + 3] if newProduct > rowProduct: rowProduct = newProduct rowResult = [lines[row][col], lines[row][col + 1], lines[row][col + 2], lines[row][col + 3], 'row:', row, 'col', col, 'row product', rowProduct] for col in range(0, 20): for row in range(0, 17): newProduct = lines[row][col] * lines[row + 1][col] * lines[row + 2][col] * lines[row + 3][col] if newProduct > colProduct: colProduct = newProduct colResult = [lines[row][col], lines[row + 1][col], lines[row + 2][col], lines[row + 3][col], 'row:', row, 'col', col, 'col product', colProduct] for row in range(0, 17): for col in range(0, 17): newProduct = lines[row][col] * lines[row + 1][col + 1] * lines[row + 2][col + 2] * lines[row + 3][col + 3] if newProduct > diaDownProduct: diaDownProduct = newProduct diaDownResult = [lines[row][col], lines[row + 1][col + 1], lines[row + 2][col + 2], lines[row + 3][col + 3], 'row:', row, 'col', col, 'dia down product', diaDownProduct] for row in range(0, 17): for col in range(0, 17): newProduct = lines[row + 3][col] * lines[row + 2][col + 1] * lines[row + 1][col + 2] * lines[row][col + 3] if newProduct > diaUpProduct: diaUpProduct = newProduct diaUpResult = [lines[row + 3][col], lines[row + 2][col + 1], lines[row + 1][col + 2], lines[row][col + 3], 'row:', row, 'col', col, 'dia up product', diaUpProduct] print(rowResult, "\n", colResult, "\n", diaDownResult, "\n", diaUpResult) resultList = [rowProduct, colProduct, diaDownProduct, diaUpProduct] print(max(resultList))
The codes are growing! It feels like this problem should be solvable in a more elegant way both mathematically and programatically. I'll go with this solution for now and maybe turn back in the future to try a new way (if I learn one).
/Ludvig
No comments:
Post a Comment