Python数据结构。
已知稀疏矩阵A和B,编程实现基于三元组顺序表实现A+B的运算。
1条回答 默认 最新
- ShowMeAI 2022-12-25 16:46关注
详细代码实现和注释如下,望采纳
class SparseMatrix: def __init__(self, rows, cols, values): self.rows = rows self.cols = cols self.values = values def add(self, other): # 初始化三元组顺序表 result_rows = [] result_cols = [] result_values = [] i = j = 0 while i < len(self.rows) and j < len(other.rows): if self.rows[i] == other.rows[j] and self.cols[i] == other.cols[j]: result_rows.append(self.rows[i]) result_cols.append(self.cols[i]) result_values.append(self.values[i] + other.values[j]) i += 1 j += 1 elif self.rows[i] < other.rows[j] or (self.rows[i] == other.rows[j] and self.cols[i] < other.cols[j]): result_rows.append(self.rows[i]) result_cols.append(self.cols[i]) result_values.append(self.values[i]) i += 1 else: result_rows.append(other.rows[j]) result_cols.append(other.cols[j]) result_values.append(other.values[j]) j += 1 # 将剩余的三元组加入结果表中 while i < len(self.rows): result_rows.append(self.rows[i]) result_cols.append(self.cols[i]) result_values.append(self.values[i]) i += 1 while j < len(other.rows): result_rows.append(other.rows[j]) result_cols.append(other.cols[j]) result_values.append(other.values[j]) j += 1 return SparseMatrix(result_rows, result_cols, result_values) # 示例 A = SparseMatrix([1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]) B = SparseMatrix([1, 2, 3, 4], [1, 2, 3, 4], [4, 3, 2, 1]) C = A.add(B) print(C.rows) # [1, 2, 3, 4] print(C.cols) # [1, 2, 3, 4] print(C.values) # [5, 5, 5, 5]
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 4无用
悬赏问题
- ¥15 宇视监控服务器无法登录
- ¥15 PADS Logic 原理图
- ¥15 PADS Logic 图标
- ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
- ¥15 DruidDataSource一直closing
- ¥20 气象站点数据求取中~
- ¥15 如何获取APP内弹出的网址链接
- ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
- ¥50 STM32单片机传感器读取错误
- ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据