defining matrix class in python

2024/11/24 4:37:42

enter image description here

Define a class that abstracts the matrix that satisfies the following examples of practice

Answer
class Matrix:def __init__(self, n, m):self.matrix = self.get_matrix(n, m)def get_matrix(self, n, m):num = 1matrix = [[None for j in range(m)] for i in range(n)]for i in range(len(matrix)):for j in range(len(matrix[i])):matrix[i][j] = numnum += 1return matrixdef get_readable_matrix_string(self, matrix):strings = []for row in matrix:strings.append(str(row))return '\n'.join(strings)  def __str__(self):return self.get_readable_matrix_string(self.matrix)def __len__(self):return len(self.matrix)def __getitem__(self, item):return self.matrix[item]def getElement(self, i, j):return self.matrix[i-1][j-1]def setElement(self, i, j, element):self.matrix[i-1][j-1] = elementdef transpose(self, matrix):return [list(i) for i in zip(*matrix)]def getTranspose(self):return self.get_readable_matrix_string(self.transpose(self.matrix))def doTranspose(self):self.matrix = self.transpose(self.matrix)def multiply(self, matrix):result = [[0 for j in range(len(matrix[i]))] for i in range(len(self.matrix))]for i in range(len(self.matrix)):for j in range(len(matrix[0])):for k in range(len(matrix)):result[i][j] += self.matrix[i][k] * matrix[k][j]return resultdef getMultiply(self, matrix):return self.get_readable_matrix_string(self.multiply(matrix))def __mul__(self, other):if isinstance(other, Matrix):return self.get_readable_matrix_string(self.multiply(other))return self.get_readable_matrix_string([[num*other for num in row] for row in self.matrix])m1 = Matrix(2, 3)
print(m1)
# [1, 2, 3]
# [4, 5, 6]
print(m1.getElement(2,2))
# 5
m1.setElement(2,2,-10)
print(m1.getTranspose())
# [1, 4]
# [2, -10]
# [3, 6]
print(m1)
# [1, 2, 3]
# [4, -10, 6]
m1.doTranspose()
print(m1)
# [1, 4]
# [2, -10]
# [3, 6]
m2 = Matrix(2,3)
print(m2)
# [1, 2, 3]
# [4, 5, 6]
print(m2.getMultiply(m1))
# [14, 2]
# [32, 2]
print(m2 * m1)
# [14, 2]
# [32, 2]
print(m1)
# [1, 4]
# [2, -10]
# [3, 6]
print(m1 * 3)
# [3, 12]
# [6, -30]
# [9, 18]
https://en.xdnf.cn/q/120577.html

Related Q&A

Why do round() and math.ceil() give different values for negative numbers in Python 3? [duplicate]

This question already has an answer here:What is the algorithmic difference between math.ceil() and round() when trailing decimal points are >= 0.5 in Python 3?(1 answer)Closed 6 years ago.Why do r…

getting the value from text file after the colon or before the colon in python

I only need the last number 25 so i can change it to int(). I have this text file:{"members": [{"name": "John", "location": "QC", "age": 25}…

How to remove the background of an object using OpenCV (Python) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 3 years ago.Improve…

How to move zeros to the end of a list [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

My program only appends one user input to list when main is looped

This is part of my code for a guessing game. I want to count the guesses of a player, and then append their name and number of guesses to a list that is later written or appended to file. As of now, it…

How to split a python dictionary for its values on matching a key

my_dict1 = {a:1, chk:{b:2, c:3}, e:{chk:{f:5, g:6}} }I would like to loop through the dict recursively and if the key is chk, split it. Expected output:{a:1, b:2, e:{f:5}} {a:1, c:3, e:{f:5}} {a:1, b:2…

PyException: ImportError: No module named domreg

I am getting the below error while running this script ("from xml.dom import minidom") from chaquopy androi application python console. PyException: ImportError: No module named domreg

Plotting polynomial with given coefficients

Im trying to plot a polynomial with coefficients given in array:input: [an,a(n-1),...,a0] output: plot of polynomial anx^n + a(n-1)x^(n-1) + ... + a0I would like to use matplotlib polt() function so I…

grouping data using unique combinations

n my below data set, I need to find unique sequences and assign them a serial no ..DataSet :user age maritalstatus product A Young married 111 B young married 222 C young Single 111 D…

Python - Sorting in ascending order in a txt file

I had a huge document that I parsed using regex to give a txt file (json.dump) similar to the following:{"stuff": [{"name": ["frfer", "niddsi", ], "number&q…