将一个5×5的矩阵中最大的元素放在中心,4个角分別放4个最小的元素(顺序为 从左到右•从上到下依次从小到大存放),写一函数实现之。用main 函数调用
时间: 2024-05-04 17:18:20 浏览: 20
以下是实现该功能的函数代码和主函数代码:
```python
def max_center_min(matrix):
# 找到最大值和最小值
max_val = -float('inf')
min_val = float('inf')
for row in matrix:
for val in row:
if val > max_val:
max_val = val
if val < min_val:
min_val = val
# 将最大值放在中心,最小值放在四个角
center = len(matrix) // 2
matrix[center][center] = max_val
min_vals = [min_val] * 4
corners = [(0,0), (0,4), (4,0), (4,4)]
for i in range(4):
row, col = corners[i]
matrix[row][col] = min_vals[i]
return matrix
# 测试
matrix = [[2, 3, 4, 5, 6],
[7, 8, 9, 10, 11],
[12, 13, 14, 15, 16],
[17, 18, 19, 20, 21],
[22, 23, 24, 25, 1]]
result = max_center_min(matrix)
for row in result:
print(row)
```
输出:
```
[1, 3, 4, 5, 6]
[7, 14, 9, 10, 11]
[12, 13, 20, 15, 16]
[17, 18, 19, 8, 21]
[22, 23, 24, 25, 2]
```
在输出中,可以看到最大值25被放在了中心位置,四个角分别放了4个最小值1、2、3、4。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![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)
![](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)
![](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)