What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?
I've seen some of the solutions of the problem and although they are in Python3, my solution has some differences.
Pylint rates it 7.27/10 and I will add docstring eventually. Some of the lines are too long(104/100) and fl
is not a good name for a file and I agree.
The main issues are comparing product
and product_temp
and calculating the sum for a diagonal from down left to upper right is inconsistent with the calculating the other products.
The code:
#!/bin/env python3
"""
https://projecteuler.net/problem=11
In a 20x20 matrix iterate over all the rows, columns,
diagonals(left up -> down right, down left -> upper right)
and find the largest product of 4 numbers in the same direction
"""
def list_ints():
with open('./textfiles/grid2020.txt') as fl:
array = [[int(x) for x in line.split()] for line in fl]
return array
def biggest_product():
grid = list_ints()
product = 0
product_temp = 0
col = 20
row = 20
for i in range(row):
for j in range(col):
#for row
if i + 3 < 20:
product_temp = grid[i][j] * grid[i + 1][j] * grid[i + 2][j] * grid[i + 3][j]
if product < product_temp:
product = product_temp
#for column
if j + 3 < 20:
product_temp = grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3]
if product < product_temp:
product = product_temp
#for diagonal from upper left to down right
if i + 3 < 20 and j + 3 < 20:
product_temp = grid[i][j] * grid[i + 1][j + 1] * grid[i + 2][j + 2] * grid[i + 3][j + 3]
if product < product_temp:
product = product_temp
#another loop from the other diagonal
#diagonal left to upeer right
for i in range(20, -1, -1):
for j in range(20):
if i + 3 < 20 and j - 3 >= 0:
product_temp = grid[i][j] * grid[i + 1][j - 1] * grid[i + 2][j - 2] * grid[i + 3][j - 3]
if product < product_temp:
product = product_temp
return product
if __name__ == '__main__':
print(biggest_product())
Edit: Now I see the comments for calculating row and col comments are reversed.