Home > OS >  print matrix in class using recursion - python
print matrix in class using recursion - python

Time:01-15

Using Python -I have a class that accepts matrix of numbers and I need to print the matrix using recursion and it prints the first array over and over again. What do I do wrong

This is the code I wrote

class Matrix:
    def __init__(self,mtx):
        self.mtx = mtx
        
    def PrintMat(self,mtx):
        if len(self.mtx)==1:
            print(self.mtx[0])
        else:
            print(self.mtx[0])
            self.PrintMat(self.mtx[1:])
            
    def properties(self):
        print(self.mtx)
        
matrix = Matrix(([1,2,3],[2,3,4]))
matrix.PrintMat(matrix)

CodePudding user response:

The function PrintMat uses the class variable instead of its paramater.

Try:

def PrintMat(self,mtx):
    if len(mtx)==1:
        print(mtx[0])
    else:
        print(mtx[0])
        self.PrintMat(mtx[1:])

CodePudding user response:

You shouldn't be passing a mtx argument- use self.mtx. Also, you'll run into issues if your matrix is empty (index error) or too long (recursion depth exceeded). Do something like this instead:

def print_matrix(self):
    for row in self.mtx:
        print(row)

You may even want to consider just making a __str__ or __repr__ method for your class that returns the matrix as a string, so you can print that. Or just use pprint.pprint to print your matrix on multiple lines if each row is sufficiently long. An example using pformat:

from pprint import pformat

class Matrix:
    def __init__(self, mtx):
        self.mtx = mtx

    def __repr__(self):
        return pformat(self.mtx)
  • Related