steff
steff

Reputation: 101

Matrix class definition

I need some help especially for b). Thank you

Define a class for matrices as follows: (a) Provide an implementation of __init__ that takes a list of lists as input and returns a new object of type matrix.

For the matrix A =

1 2
3 4

a user could enter A = matrix( [[1,2],[3,4]]).

(b) Provide an implementation of __repr__ that returns a string representation of a matrix, printing each row in a separate line, e.g. printing A as:

1, 2
3, 4

Upvotes: 2

Views: 4396

Answers (2)

badp
badp

Reputation: 11813

For a), it really depends on how you want to store the matrix. Storing the matrix as a list of lists, as is, is probably fine for most uses, but I don't know what your use is exactly. Matrixes have constraints that lists of lists lack (all rows have the same numbers of items of the same type); it will be up to this class to make sure that the restraints hold true. That said, if this is the entirety of the assignment, just using the list of lists as is will be okay.

Thus, you might want to make some doublechecking on the input. The len() method will come in handy.

Here's what your constructor needs to be able to handle, eventually using Exceptions:

  • Matrix([])
  • Matrix("Hi")
  • Matrix([1])
  • Matrix([1], [2])
  • Matrix([1], [2, 3])
  • Matrix([1,2], [3, 4])
  • Matrix([1.0, 2.0], [3.0, 4.0])
  • Matrix([1.0 + 2j, 3.0 - 4j], [5.0 + 6.0j, 7.0 + 8.0j])
  • a = []; a = [a, a]; Matrix(a)

For b), well, all you need to do is put a ", " between every row element and a "\n" between every row. If only there was an easy way to do that...

Upvotes: 6

Alexander Gessler
Alexander Gessler

Reputation: 46607

class matrix(object):
   def __init__(self,matrix)
      self.matrix = matrix

   def __repr__(self):
      return '\n'.join(','.join(str(m) for m in n) for n in self.matrix)

Since this is homework, I strongly recommend you to look up everything you don't know in the docs and to play around with it.

Upvotes: 3

Related Questions