解题思路:遍历矩阵中各个元素,有可能直接是数字,也可能是字符串表达式,输入时碰到数字直接转为int,便于后续条件判断
碰到表达式要进行处理;1.判断是三种操作中哪一个2.取出左上角和右下角的坐标3.代入具体的操作函数,返回对应值
注意事项:1.在操作函数内部也需要遍历矩阵,所以同样要处理字符串
2.优化--字符串处理部分可以封装到函数,提高代码复用性,后续赋值部分不行,处理方法不同
参考代码:
import math def SUM(upper_left, lower_right): sum_up = 0 for a in range(int(upper_left[0]) - 1, int(lower_right[0])): for b in range(int(upper_left[1]) - 1, int(lower_right[1])): if type(matrix[a][b]) != str: sum_up += matrix[a][b] else: cur = matrix[a][b][3:].replace("(", "").replace(")", "") upper_left, lower_right = cur.split(":") upper_left = upper_left.split(",") lower_right = lower_right.split(",") if matrix[a][b][:3] == "SUM": # 递归调用其它操作函数,因为题目保证了不会死锁 sum_up += SUM(upper_left, lower_right) # 处理得到数字直接相加即可,因为是求和 elif matrix[a][b][:3] == "AVG": sum_up += AVG(upper_left, lower_right) else: sum_up += STD(upper_left, lower_right) return sum_up def AVG(upper_left, lower_right):#求平均值,先求和再除以元素个数 avg = SUM(upper_left, lower_right) / ( (int(lower_right[0]) - int(upper_left[0]) + 1) * (int(lower_right[1]) - int(upper_left[1]) + 1)) return avg def STD(upper_left, lower_right): avg = AVG(upper_left, lower_right) sum_up = 0 for p in range(int(upper_left[0]) - 1, int(lower_right[0])): # 相同的处理逻辑 for q in range(int(upper_left[1]) - 1, int(lower_right[1])): if type(matrix[p][q]) != str:#如果已经是数字直接计算即可 sum_up += (matrix[p][q] - avg) ** 2 else: cur = matrix[p][q][3:].replace("(", "").replace(")", "") upper_left, lower_right = cur.split(":") upper_left = upper_left.split(",") lower_right = lower_right.split(",") if matrix[p][q][:3] == "SUM": sum_up += (SUM(upper_left, lower_right) - avg) ** 2 # 方差的计算和求和不同,不了解请仔细查看题目 elif matrix[p][q][:3] == "AVG": sum_up += (AVG(upper_left, lower_right) - avg) ** 2 else: sum_up += (STD(upper_left, lower_right) - avg) ** 2 variance = sum_up / ( (int(lower_right[0]) - int(upper_left[0]) + 1) * (int(lower_right[1]) - int(upper_left[1]) + 1)) # 求方差 return math.sqrt(variance) #求标准差 n, m = map(int, input().strip().split()) matrix = [] for i in range(n):#读取输入 temp = input().split() for j in range(len(temp)): if "0" <= temp[j][0] <= "9":#判断是数字还是表达式,是数字直接转int型 temp[j] = int(temp[j]) matrix.append(temp) for x in range(n):#遍历矩阵 for y in range(m): if type(matrix[x][y]) == str: cur = matrix[x][y][3:].replace("(", "").replace(")", "") upper_left, lower_right = cur.split(":") upper_left = upper_left.split(",") lower_right = lower_right.split(",") if matrix[x][y][:3] == "SUM": matrix[x][y] = SUM(upper_left, lower_right) # 处理结束后直接修改原矩阵,便于后续函数调用 elif matrix[x][y][:3] == "AVG": matrix[x][y] = AVG(upper_left, lower_right) else: matrix[x][y] = STD(upper_left, lower_right) print('{:.2f}'.format(matrix[x][y]), end = " ") print()
0.0分
1 人评分
矩形面积交 (C语言代码)浏览:1553 |
C语言程序设计教程(第三版)课后习题10.5 (C语言代码)浏览:767 |
【回文数(二)】 (C++代码)浏览:932 |
C语言程序设计教程(第三版)课后习题4.9 (C语言代码)浏览:949 |
剪刀石头布 (C语言代码)浏览:802 |
C语言程序设计教程(第三版)课后习题8.8 (C语言代码)浏览:895 |
Cylinder (C语言描述,蓝桥杯)浏览:1279 |
C语言程序设计教程(第三版)课后习题4.9 (C语言代码)浏览:727 |
2003年秋浙江省计算机等级考试二级C 编程题(1) (C语言代码)浏览:721 |
杨辉三角 (C语言代码)浏览:504 |