MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / largest_product

Function largest_product

project_euler/problem_011/sol1.py:30–68  ·  view source on GitHub ↗
(grid)

Source from the content-addressed store, hash-verified

28
29
30def largest_product(grid):
31 n_columns = len(grid[0])
32 n_rows = len(grid)
33
34 largest = 0
35 lr_diag_product = 0
36 rl_diag_product = 0
37
38 # Check vertically, horizontally, diagonally at the same time (only works
39 # for nxn grid)
40 for i in range(n_columns):
41 for j in range(n_rows - 3):
42 vert_product = grid[j][i] * grid[j + 1][i] * grid[j + 2][i] * grid[j + 3][i]
43 horz_product = grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3]
44
45 # Left-to-right diagonal (\) product
46 if i < n_columns - 3:
47 lr_diag_product = (
48 grid[i][j]
49 * grid[i + 1][j + 1]
50 * grid[i + 2][j + 2]
51 * grid[i + 3][j + 3]
52 )
53
54 # Right-to-left diagonal(/) product
55 if i > 2:
56 rl_diag_product = (
57 grid[i][j]
58 * grid[i - 1][j + 1]
59 * grid[i - 2][j + 2]
60 * grid[i - 3][j + 3]
61 )
62
63 max_product = max(
64 vert_product, horz_product, lr_diag_product, rl_diag_product
65 )
66 largest = max(largest, max_product)
67
68 return largest
69
70
71def solution():

Callers 1

solutionFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected