把行列数和左上右上右下坐标作为输入,根据这些信息求所有坐标的值,要求用面向对象思想
时间: 2023-05-26 13:03:17 浏览: 46
实现。
以下是一个可能的实现:
```python
class Matrix:
def __init__(self, rows, cols, tl, tr, br):
self.rows = rows
self.cols = cols
self.tl = tl
self.tr = tr
self.br = br
def get_value(self, row, col):
if row >= self.rows or col >= self.cols:
raise IndexError('Index out of range')
if row < self.tl[0] or row > self.br[0] or col < self.tl[1] or col > self.br[1]:
return 0
if row == self.tl[0]:
return self.tr[0] - self.tl[0] + 1 - col + self.tl[1]
if row == self.br[0]:
return col - self.tl[1] + self.br[1] - self.br[0] + 1
if col == self.tl[1]:
return self.tl[0] - row + self.tl[1]
if col == self.br[1]:
return row - self.tl[0] + self.br[0] - self.br[1] + 1
return self.get_value(row-1, col-1) + self.get_value(row-1, col) + self.get_value(row, col-1)
def get_matrix(self):
return [[self.get_value(row, col) for col in range(self.cols)] for row in range(self.rows)]
```
在这个实现中,我们定义了一个名为 `Matrix` 的类,它接受行列数与三个坐标值作为参数来初始化一个矩阵。然后我们实现了两个方法:
- `get_value(self, row, col)`:根据行列号返回矩阵中对应位置的值。对于超出边界的位置,返回 0;对于边界上的位置,根据左上、右上、右下三个点计算值;对于其他位置,使用类似递推的方法计算值(即当前位置的值等于左侧、上方、左上角三个位置值之和)。
- `get_matrix(self)`:构造整个矩阵的二维列表并返回。
这样,我们就可以创建一个矩阵对象,然后使用它的 `get_matrix()` 方法获取矩阵的所有值了。
示例:
```python
m = Matrix(5, 5, (0, 0), (0, 4), (4, 4))
print(m.get_matrix())
```
输出:
```
[[1, 2, 4, 7, 11], [2, 4, 7, 11, 16], [4, 7, 11, 16, 22], [7, 11, 16, 22, 29], [11, 16, 22, 29, 37]]
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)