原题链接:蓝桥杯2015年第六届真题-表格计算
解题思路:遍历矩阵中各个元素,有可能直接是数字,也可能是字符串表达式,输入时碰到数字直接转为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语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复