Python 实现简单的稀疏矩阵

#!/usr/bin/python 
# -*- coding: utf-8 -*-

'''
Created on 2015-1-14
@author: beyondzhou
@name: mysparsermatrix.py
'''

# Implementation of the Sparse Matrix ADT using a list
class SparseMatrix:
    # Create a sparse matrix of size numRows * numCols initialied to 0
    def __init__(self, numRows, numCols):
        self._numRows = numRows
        self._numCols = numCols
        self._elementList = list()

    # Return the number of rows in the matrix
    def numRows(self):
        return self._numRows

    # Return the number of columns in the matrix
    def numCols(self):
        return self._numCols

    # Return the value of element (i, j): x[i, j]
    def __getitem__(self, ndxTuple):
        pass

    # Set the value of element(i,j) to the value s
    def __setitem__(self, ndxTuple, scalar):
        ndx = self._findPosition(ndxTuple[0], ndxTuple[1])
        if ndx is not None:
            if scalar != 0.0:
                self._elementList[ndx].value = scalar
            else:
                self._elementList.pop(ndx)
        else:
            if scalar != 0.0:
                element = _MatrixElement(ndxTuple[0], ndxTuple[1], scalar)
                self._elementList.append(element)

    # Scale the matrix by the given scalar
    def scaleBy(self, scalar):
        for element in self._elementList:
            element.value *= scalar

    # Add methods
    def __add__(self, rhsMatrix):
        assert rhsMatrix.numRows() == self.numRows() and \
                rhsMatrix.numCols() == self.numCols(), \
               "Matrix sizes not compatible for the add operation."

        # Create the new matrix
        newMatrix = SparseMatrix(self.numRows(), self.numCols())

        # Duplicate the lhs matrix, the elements are mutable, thus we must
        # create new objects and not simply copy the references.
        for element in self._elementList:
            dupElement = _MatrixElement(element.row, element.col, element.value)
            newMatrix._elementList.append(dupElement)

        # Iterate through each non-zero element of the rhsMatrix
        for element in rhsMatrix._elementList:
            # Get the value of the corresponding element in the new matrix
            value = newMatrix[element.row, element.col]
            value += element.value
            # Store the new value back to the new matrix
            newMatrix[element.row, element.col] = value

        # return the new matrix
        return newMatrix

    # Sub method
    def __sub__(self, rhsMatrix):
        assert rhsMatrix.numRows() == self.numRows() and \
                rhsMatrix.numCols() == self.numCols(), \
               "Matrix sizes not compatible for the add operation."

        # Create the new matrix
        newMatrix = SparseMatrix(self.numRows(), self.numCols())

        # Duplicate the lhs matrix, the elements are mutable, thus we must
        # create new objects and not simply copy the references.
        for element in self._elementList:
            dupElement = _MatrixElement(element.row, element.col, element.value)
            newMatrix._elementList.append(dupElement)

        # Iterate through each non-zero element of the rhsMatrix
        for element in rhsMatrix._elementList:
            # Get the value of the corresponding element in the new matrix
            value = newMatrix[element.row, element.col]
            value -= element.value
            # Store the new value back to the new matrix
            newMatrix[element.row, element.col] = value

        # return the new matrix
        return newMatrix     

    # Mul method
    def __mul__(self, rhsMatrix):
        pass

    # Helper method used to find a specific matrix elemenet (row, col) in the 
    # list of non-zeo entries, None is returned if the element is not found
    def _findPostion(self, row, col):
        n = len(self._elementList)
        for i in range(n):
            if row == self._elementList[i].row and \
                col == self._elementList[i].col:
                return i
        return None

# Storage class for holding the non-zero matrix elements
class _MatrixElement:
    def __init__(self, row, col, value):
        self.row = row
        self.col = col
        self.value = value

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值