Python:打印列时缺少数字

时间:2018-11-11 23:09:53

标签: python matrix logic digits

我对为什么我的“矩阵”列中的数字无法正确打印感到困惑。

它缺少第一个数字之后的尾随数字。但是,它执行正确的操作。我不确定为什么输出会是这样,并且已经查看了我的代码几次。我可能没有抓到东西。

希望您能帮助我查找逻辑错误。

class Matrix:
    def __init__(self, Rowsp=[[]]):  
        """Matrix Constructor"""
        self.Rowsp = Rowsp
        self.Colsp = [[self.Rowsp[j][i] for j in range(len(self.Rowsp))] for i in range(len(self.Rowsp[0]))]

    def copy(self):
        """ 
        Returns a copy of the matrix for calculations
        """
        copy = []
        rows = len(self.Rowsp)
        cols = len(self.Rowsp[0])

        for i in range(rows):
            copy.append(list())
            for j in range(cols):
                copy[i].append(self.Rowsp[i][j])

        return Matrix(copy)

设置者

def setCol(self, j, u):
    """
    changes the j-th column to be the list u. 
    If u is not the same length as the existing columns, 
    then the constructor should raise a ValueError 
    with the message Incompatible column length.
    """
    rows = len(self.Rowsp)
    if (len(u) != rows):
        #raise ValueError - SWAP OUT FOR VAL ERROR
        print("ERROR: Incompatible column length")
    else:
        j -= 1
        for i in range(rows):
            self.Rowsp[i][j] = u[i]

def setRow(self, i, v):
    """
    changes the i-th row to be the list v. 
    If v is not the same length as the existing rows, 
    then the constructor should raise a ValueError 
    with the message Incompatible row length. 
    """
    if len(self.Rowsp[0]) != len(v):
        #raise ValueError - SWAP OUT FOR VAL ERROR
        print("ERROR: Incompatible row length")
    else:
        self.Rowsp[i - 1] = v

def setEntry(self, i, j, a):
    """
    changes the existing a_{ij} entry in the matrix to a 
    """
    self.Rowsp[i - 1][j - 1] = a

信件

def getCol(self, j):
    """
    returns the j-th column as a list. 
    """
    return self.Colsp[j - 1]

def getRow(self, i):
    """
    returns the i-th row as a list v.  
    """
    return self.Rowsp[i - 1]

def getEntry(self, i, j):
    """
    returns the existing a_{ij} entry in the matrix.
    """
    return self.Rowsp[i - 1][j - 1]

def getColSpace(self):
    """
    returns the list of vectors that make up the column space of the matrix object 
    """
    c = self.Colsp.copy()
    return c

def getRowSpace(self):
    """
    returns the list of vectors that make up the row space of the matrix object 
    """
    r = self.Rowsp.copy()
    return r

测试用例

print("The 2nd row is:", A.getRow(2))
print("The 3rd column is:", A.getCol(3))
print()

A.setRow(2, [40, 50])
A.setCol(2, [30, 4, 1])

print(A)

我的结果:

The 2nd row is: [40, 50, 60]
The 3rd column is: [3, 6]

ERROR: Incompatible row length
ERROR: Incompatible column length
10  20  30
40  50  60

我应该得到的:

The 2nd row is: [40, 50, 60]
The 3rd column is: [30, 60]

ERROR: Incompatible row length.
ERROR: Incompatible column space.
10  20  30  
40  50  60  

0 个答案:

没有答案