我正在读取和写入二维数组中的值。我发现每次从单元格读取和写入时说 grid[row][column] 有点冗长,特别是因为我喜欢处理一个变量 cell = (i,j) 来跟踪单元格而不是两个变量行、列 = i、j。我想做如下的事情:
def value(cell):
row, column = cell
return grid[row][column]
value(cell) += 5
并更新网格中的实际单元格。
我相信使用 property 的类中可以实现该功能,但我想找到一种方法来做到这一点,而不必围绕它创建一个类。有什么办法可以做到吗?
这是我现在正在使用的完整代码:
from typing import List
from itertools import product
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
def cell_above(cell):
row, column = cell
return (row-1, column)
def cell_to_the_left(cell):
row, column = cell
return (row, column-1)
def value(cell):
row, column = cell
return grid[row][column]
def add_value(cell, val):
row, column = cell
grid[row][column] += val
first_row = ((0, i) for i in range(1, n))
first_column = ((j, 0) for j in range(1, m))
cells = product(range(1, m), range(1, n))
last_cell = (m-1, n-1)
for cell in first_row:
add_value(cell, value(cell_to_the_left(cell)))
for cell in first_column:
add_value(cell, value(cell_above(cell)))
for cell in cells:
add_value(cell, min(value(cell_above(cell)), value(cell_to_the_left(cell))))
return value(last_cell)
我希望这段代码的底部看起来更像这样:
for cell in first_row:
value(cell) += value(cell_to_the_left(cell))
for cell in first_column:
value(cell) += value(cell_above(cell))
for cell in cells:
value(cell) += min(value(cell_above(cell)), value(cell_to_the_left(cell)))
我尝试了以下方法:
def value_setter(cell):
row, column = cell
def set_value(val):
grid[row][column] = val
return set_value
def value(cell):
row, column = cell
return property
for cell in first_row:
val = value(cell)
val += value(cell_to_the_left(cell))
我从这段代码中得到以下错误:
TypeError:+= 不支持的操作数类型:“property”和“property” val += 值(cell_to_the_left(cell)) minPathSum 中的第 34 行 (Solution.py) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ret = Solution().minPathSum(param_1) _driver 中的第 59 行 (Solution.py) _司机()
(Solution.py)中的第 70 行
有什么方法可以使其与内置属性函数或任何其他模仿我正在寻找的行为的功能一起工作?
无论是否为类,都无法分配给函数调用表达式。不过,您可以分配给切片表达式,例如
value[cell]
,它将调用* value
的__getitem__
和__setitem__
:
class GridWrapper:
"""
Converts 2D tuple item access to nested item access.
"""
def __init__(self, grid):
self.grid = grid
def __getitem__(self, coord):
row, column = coord
return self.grid[row][column]
def __setitem__(self, coord, value):
row, column = coord
self.grid[row][column] = value
value = GridWrapper(grid)
* 实际上,当您使用 __iadd__
时,更愿意调用该值的
+=
,但这在任何情况下都是正确的行为