Python数据结构。
已知稀疏矩阵A和B,编程实现基于三元组顺序表实现A+B的运算。
已知稀疏矩阵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 delphi webbrowser组件网页下拉菜单自动选择问题
- ¥15 linux驱动,linux应用,多线程
- ¥20 我要一个分身加定位两个功能的安卓app
- ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
- ¥15 IAR程序莫名变量多重定义
- ¥15 (标签-UDP|关键词-client)
- ¥15 关于库卡officelite无法与虚拟机通讯的问题
- ¥15 目标检测项目无法读取视频
- ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
- ¥100 求采集电商背景音乐的方法