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

Function solve

project_euler/problem_345/sol1.py:67–92  ·  view source on GitHub ↗

Finds the max sum for array `arr` starting with row index `row`, and with columns included in `cols`. `cache` is used for caching intermediate results. >>> solve(arr=np.array([[1, 2], [3, 4]]), row=0, cols={0, 1}, cache={}) 5

(arr: NDArray, row: int, cols: set[int], cache: dict[str, int])

Source from the content-addressed store, hash-verified

65
66
67def solve(arr: NDArray, row: int, cols: set[int], cache: dict[str, int]) -> int:
68 """
69 Finds the max sum for array `arr` starting with row index `row`, and with columns
70 included in `cols`. `cache` is used for caching intermediate results.
71
72 >>> solve(arr=np.array([[1, 2], [3, 4]]), row=0, cols={0, 1}, cache={})
73 5
74 """
75
76 cache_id = f"{row}, {sorted(cols)}"
77 if cache_id in cache:
78 return cache[cache_id]
79
80 if row == len(arr):
81 return 0
82
83 max_sum = 0
84 for col in cols:
85 new_cols = cols - {col}
86 max_sum = max(
87 max_sum,
88 int(arr[row, col])
89 + solve(arr=arr, row=row + 1, cols=new_cols, cache=cache),
90 )
91 cache[cache_id] = max_sum
92 return max_sum
93
94
95def solution(matrix_str: list[str] = MATRIX_2) -> int:

Callers 1

solutionFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected