python - Is there a one line code to find maximal value in a matrix? -
to find maximal value in matrix of numbers, can code 5 lines solve problem:
ans = matrix[0][0] x in range(len(matrix)): y in range(len(matrix[0])): ans = max(ans, matrix[x][y]) return ans is there 1 line solution problem? 1 came pretty awkward actually:
return max(max(matrix, key=max)) or
return max(map(max, matrix))
you can use generator expression find maximum in matrix. way can avoid building full list of matrix elements in memory.
maximum = max(max(row) row in matrix) instead of list comprehension given in previous answer here
maximum = max([max(row) row in matrix]) this pep (the rationale section):
...many of use cases not need have full list created in memory. instead, they need iterate on elements 1 @ time.
...
generator expressions useful functions sum(), min(), , max() reduce iterable input single value
...
the utility of generator expressions enhanced when combined reduction functions sum(), min(), , max().
also, take @ post: generator expressions vs. list comprehension.
Comments
Post a Comment