Python数据结构。
已知稀疏矩阵A和B,编程实现基于三元组顺序表实现A+B的运算。
![](https://profile-avatar.csdnimg.cn/default.jpg!4)
已知稀疏矩阵A和B,编程实现基于三元组顺序表实现A+B的运算。
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
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 metadata提取的PDF元数据,如何转换为一个Excel
- ¥15 关于arduino编程toCharArray()函数的使用
- ¥100 vc++混合CEF采用CLR方式编译报错
- ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
- ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
- ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
- ¥50 如何openEuler 22.03上安装配置drbd
- ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
- ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
- ¥15 Windows11, backspace, enter, space键失灵