I made this code and it works but I get one error, it doesn't give the exact output I need. I get too much spaces, how can I Fix this error: AssertionError: '14 10 12 \n13 11 12 \n10 10 16 \n' != '14 10 12\n13 11 12\n10 10 16\n'
I made this code and it works but I get one error, it doesn't give the exact output I need. I get too much spaces, how can I Fix this error:
AssertionError: '14 10 12 \n13 11 12 \n10 10 16 \n' != '14 10 12\n13 11 12\n10 10 16\n'
class Matrix:
def __init__(self, rows):
self.list1 = rows
def __str__(self):
res = ""
for i in range(len(self.list1)):
for j in range(len(self.list1[i])):
res = res + "{:2d}".format(self.list1[i][j]) + " "
res = res + "\n"
return res
def scale(self, w):
nl = []
for i in range(len(self.list1)):
nl.append([])
for j in range(len(self.list1[i])):
nl[i].append(self.list1[i][j] * w)
return Matrix(nl)
def transpose(self):
nl = [[None for j in range(len(self.list1[i]))] for i in range(len(self.list1))]
for i in range(len(self.list1)):
for j in range(len(self.list1[i])):
nl[j][i] = self.list1[i][j]
return Matrix(nl)
def multiply(self, b):
nl = [[0 for j in range(len(self.list1[i]))] for i in range(len(self.list1))]
if len(self.list1[0]) == len(b.list1):
for i in range(len(self.list1)):
for j in range(len(b.list1[0])):
for k in range(len(b.list1)):
nl[i][j] += self.list1[i][k] * b.list1[k][j]
return Matrix(nl)
else:
return None
# repr is similar to __str__, but __str__ is used when
# printing a value, __repr__ when showing a value in
# the interpreter.
# repr is intended to be an unambiguous, complete representation
# of the object, while str is intended to be nicely readable
# for this object they are the same
def __repr__(self):
return str(self)
if __name__ == "__main__":
m = Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
m = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
n = m.scale(2)
print(n)
print(m.transpose())
e = Matrix([[1, 2, 3], [2, 1, 3], [3, 2, 1]])
print(e.multiply(e))
print(e.__repr__())
Step by step
Solved in 4 steps with 3 images