Answer the question
In order to leave comments, you need to log in
Python. How to create a matrix?
Good day to all. I study at the correspondence department. Help me overcome the problem. I'm trying to figure out the Python language.
The task sounds like this:
Create an integer matrix A of size MxN and fill it with single-valued random numbers from the range from 0 to 9. The matrix must be of type int[,]. The M and N values are entered from the keyboard. Display the original matrix line by line on the screen.
Remove from the matrix the first row that has the maximum sum of its elements. Display the new matrix line by line on the screen. Determining the number of the first row that has the maximum sum of its elements should be written as a function.
I would be grateful for any hint
Answer the question
In order to leave comments, you need to log in
>>> import random
>>> M,N = 5,6
>>> matrix = [[random.randrange(0,10) for y in range(M)] for x in range(N)]
>>> matrix
[[0, 3, 1, 3, 5], [5, 8, 8, 0, 5], [8, 9, 8, 5, 2], [7, 7, 3, 9, 9], [0, 1, 1, 3, 8], [5, 1, 1, 4, 6]]
>>> for im in range(N):
... print matrix[im]
...
[0, 3, 1, 3, 5]
[5, 8, 8, 0, 5]
[8, 9, 8, 5, 2]
[7, 7, 3, 9, 9]
[0, 1, 1, 3, 8]
[5, 1, 1, 4, 6]
>>> def find_max(m):
... max_sum = 0
... index = -1
... for x in range(N):
... if sum(m[x])>max_sum:
... max_sum=sum(m[x])
... index=x
... return max_sum, index
...
>>> find_max(matrix)
(35, 3)
>>> max_value,index = find_max(matrix)
>>> matrix.remove(matrix[index])
>>> for im in range(N):
... print matrix[im]
...
[0, 3, 1, 3, 5]
[5, 8, 8, 0, 5]
[8, 9, 8, 5, 2]
[0, 1, 1, 3, 8]
[5, 1, 1, 4, 6]
Rewrote the solution in OOP style:
import random
class Matrix:
def __init__(self, row, col):
self.n = row
self.matrix = [[random.randrange(0, 10) for a in range(col)] for b in range(row)]
def print(self):
matrix = self.matrix
for im in range(len(matrix)):
print(matrix[im])
def find_max(self):
max_sum = 0
n = self.n
m = self.matrix
index = -1
for x in range(n):
if sum(m[x]) > max_sum:
max_sum = sum(m[x])
index = x
print("максимум: %s, индекс: %s" % (max_sum, index))
return max_sum, index
def remove_max_row(self):
matrix = self.matrix
n = self.n
max_value, index = self.find_max()
matrix.remove(matrix[index])
for im in range(n-1):
print(matrix[im])
Matrix(5, 5).print()
print('-'*100)
Matrix(5, 5).find_max()
print('='*100)
Matrix(5, 5).remove_max_row()
instead of errors with creating a matrix 3 times when using the class
d=Matrix(5, 5);
d.print()
print('-'*100)
#Matrix(5, 5).find_max()
print('='*100)
d.remove_max_row()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question