Home > Enterprise >  Transposing matrix twice using classes without numpy
Transposing matrix twice using classes without numpy

Time:12-15

I need to implement a method transpose() that returns a new matrix that has been transposed. It also has to print out a string of that matrix. It works when using matrix.transpose() but it doesn't work when using matrix.transpose().transpose() because transpose() returns a string. I can't use numpy or add more input to the methods. How would I go about this?

from copy import deepcopy


class Matrix:
    def __init__(self, rows):
        self.rows = rows[:]
    def transpose(self):
            copy = deepcopy(self.rows)
            transposed = [[copy[j][i] for j in range(len(copy))] for i in range(len(copy[0]))]

        matrix = ''
        for element in transposed:
            for i in element:
                matrix  = '-' % ((i))
                matrix  = ' '
            matrix = matrix[:-1]
            matrix  = '\n'


       return matrix

a = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

CodePudding user response:

You can create a new Matrix object in transpose and return that after printing its content. For convenience I moved your printing code to a method for converting the matrix to a string (Note that a method called __repr__ will be implicit called by print). Code:

from copy import deepcopy

class Matrix:
     def __init__(self, rows):
         self.rows = rows[:]

     def transpose(self):
         copy = deepcopy(self.rows)
         transposed = [[copy[j][i] for j in range(len(copy))] for i in range(len(copy[0]))]
         transposed_matrix = Matrix(transposed)
         print(transposed_matrix)
         return transposed_matrix

     def __repr__(self):
         matrix = ''
         for element in self.rows:
             for i in element:
                 matrix  = '-' % ((i))
                 matrix  = ' '
             matrix = matrix[:-1]
             matrix  = '\n'
         return matrix

Additional improvements:

  • in transpose you can change the matrix transposition to transposed = list(map(list, zip(*self.rows)))
  • use format string instead of '-' % ((i)) -> f'{i:2}'
  • join is very helpful for formatting the matrix: return '\n'.join(' '.join(f'{i:2}' for i in row) for row in self.rows)

Now the full code looks like this

class Matrix:
     def __init__(self, rows):
         self.rows = rows[:]

     def transpose(self):
         transposed = list(map(list, zip(*self.rows)))
         transposed_matrix = Matrix(transposed)
         print(transposed_matrix)
         return transposed_matrix

     def __repr__(self):
         return '\n'.join(' '.join(f'{i:2}' for i in row) for row in self.rows)
  • Related