I have this code wrote in python 3:
matrix = []
loop = True
while loop:
line = input()
if not line:
loop = False
values = line.split()
row = [int(value) for value in values]
matrix.append(row)
print('n'.join([' '.join(map(str, row)) for row in matrix]))
print('matrix saved')
an example of returned matrix would be [[1,2,4],[8,9,0]].Im wondering of how I could find the maximum and minimum value of a matrix? I tried the max(matrix) and min(matrix) built-in function of python but it doesnt work.
Thanks for your help!
asked Apr 30, 2014 at 23:27
2
One-liner:
for max:
matrix = [[1, 2, 4], [8, 9, 0]]
print (max(map(max, matrix))
9
for min:
print (min(map(min, matrix))
0
answered Feb 10, 2020 at 5:00
eugeneugen
1,2199 silver badges15 bronze badges
If you don’t want to use new data structures and are looking for the smallest amount of code possible:
max_value = max([max(l) for l in matrix])
min_value = min([min(l) for l in matrix])
If you don’t want to go through the matrix twice:
max_value = max(matrix[0])
min_value = min(matrix[0])
for row in matrix[1:]:
max_value = max(max_value, max(row))
min_value = min(min_value, min(row))
answered Dec 10, 2019 at 10:01
AdelaNAdelaN
3,2962 gold badges24 silver badges44 bronze badges
Use the built-in functions max()
and min()
after stripping the list of lists:
matrix = [[1, 2, 4], [8, 9, 0]]
dup = []
for k in matrix:
for i in k:
dup.append(i)
print (max(dup), min(dup))
This runs as:
>>> matrix = [[1, 2, 4], [8, 9, 0]]
>>> dup = []
>>> for k in matrix:
... for i in k:
... dup.append(i)
...
>>> print (max(dup), min(dup))
(9, 0)
>>>
answered Apr 30, 2014 at 23:52
A.J. UppalA.J. Uppal
19k6 gold badges45 silver badges76 bronze badges
0
If you are going with the solution of flattening matrix in an array, instead of inner loop you can just use extend:
big_array = []
for arr in matrix:
big_array.extend(arr)
print(min(big_array), max(big_array))
answered Oct 13, 2019 at 17:45
SerjikSerjik
10.4k7 gold badges61 silver badges70 bronze badges
Try
largest = 0
smallest = 0
count = 0
for i in matrix:
for j in i:
if count == 0:
largest = j
smallest = j
count = 1
if j > largest:
largest = j
if j < smallest:
smallest = j
UPDATE
For splitting
largest = 0
count = 0
for i in matrix:
for j in i:
if count == 0:
largest = j
if j > largest:
largest = j
and do the same thing for smallest
answered Apr 30, 2014 at 23:37
Newyork167Newyork167
4945 silver badges9 bronze badges
3
here is what i came up with
M = [[1,2,4],[8,9,0]]
def getMinMax( M ):
maxVal = 0
for row in M:
if max(row) > maxVal: maxVal = max(row)
minVal = maxVal*1
for row in M:
if min(row) < minVal: minVal = min(row)
return ( minVal, maxVal )
getMinMax( M )
// Result: (0, 9) //
answered May 1, 2014 at 0:04
You could first decide to flatten this matrix and then find the corresponding maximum and minimum values as indicated below
Convert the matrix to a numpy array
import numpy as np
matrix = np.array([[1, 2, 4], [8, 9, 0]])
mat_flattened = matrix.flatten()
min_val = min(mat_flattened)
max_val = max(mat_flattened)
0
Given a matrix, the task is to find the maximum element of each row.
Examples:
Input : [1, 2, 3] [1, 4, 9] [76, 34, 21] Output : 3 9 76 Input : [1, 2, 3, 21] [12, 1, 65, 9] [1, 56, 34, 2] Output : 21 65 56
Method 1: The idea is to run the loop for no_of_rows. Check each element inside the row and find for the maximum element. Finally, print the element.
Below is the implementation :
Python
import
numpy
def
maxelement(arr):
no_of_rows
=
len
(arr)
no_of_column
=
len
(arr[
0
])
for
i
in
range
(no_of_rows):
max1
=
0
for
j
in
range
(no_of_column):
if
arr[i][j] > max1:
max1
=
arr[i][j]
print
(max1)
arr
=
[[
3
,
4
,
1
,
8
],
[
1
,
4
,
9
,
11
],
[
76
,
34
,
21
,
1
],
[
2
,
1
,
4
,
5
]]
maxelement(arr)
Output :
8 11 76 5
Time Complexity: O(N^2), where N is the number of rows in the matrix.
Space Complexity: O(1), as no extra space is required for the algorithm.
Method 2: By calculating max element Each list of list of lists using the max() function
Python3
arr
=
[[
3
,
4
,
1
,
8
],
[
1
,
4
,
9
,
11
],
[
76
,
34
,
21
,
1
],
[
2
,
1
,
4
,
5
]]
for
i
in
arr:
print
(
max
(i))
Time complexity: O(n*m), where n is the number of rows and m is the number of columns in the matrix.
Auxiliary space: O(1), as we are only using a constant amount of extra space to store the maximum value of each row.
Another approach that could be used to find the maximum element of each row in a matrix is to use the built-in map() function. The map() function applies a given function to each element of a given iterable (such as a list or a matrix). In this case, we can use the map() function to apply the max() function to each row of the matrix.
Here is an example of how this approach could be implemented:
Python3
def
find_max_element(matrix):
return
list
(
map
(
lambda
row:
max
(row), matrix))
matrix
=
[[
3
,
4
,
1
,
8
],
[
1
,
4
,
9
,
11
],
[
76
,
34
,
21
,
1
],
[
2
,
1
,
4
,
5
]]
max_elements
=
find_max_element(matrix)
print
(max_elements)
Time complexity: O(n * m), where n is the number of rows and m is the number of columns in the matrix.
Auxiliary Space: O(n), as we are creating a new list to store the maximum elements of each row.
Method#4: Using the Recursive method.
The find_max_recursive function takes a matrix as input, along with an optional index variable i (which is initially set to 0) and a result list res (which is initially empty). The function returns a list of the maximum element in each row of the matrix.
The function first checks if it has reached the end of the matrix (i.e., if i is equal to the length of the matrix). If so, it returns the result list. Otherwise, it finds the maximum element in the current row using the built-in max function, and appends it to the result list. It then recursively calls itself with the index of the next row and the updated result list.
Python3
def
find_max_recursive(matrix, i
=
0
, res
=
[]):
if
i
=
=
len
(matrix):
return
res
max_val
=
max
(matrix[i])
res.append(max_val)
return
find_max_recursive(matrix, i
+
1
, res)
matrix
=
[[
3
,
4
,
1
,
8
],
[
1
,
4
,
9
,
11
],
[
76
,
34
,
21
,
1
],
[
2
,
1
,
4
,
5
]]
max_elements
=
find_max_recursive(matrix)
print
(max_elements)
The time complexity of this function is O(n^2), where n is the size of the input matrix. This is because the function iterates over each element in the matrix once to find the maximum value in each row, resulting in n iterations. Additionally, finding the maximum value in each row requires iterating over each element in the row, resulting in another n iterations. Therefore, the total number of iterations is n^2.
The auxiliary space of this function is also O(n^2), as the result array ‘res’ is being appended with the maximum element from each row in the matrix. Since the matrix has n^2 elements, the result array will also have a maximum of n^2 elements, leading to the O(n^2) space complexity.
Method#5: Using the lambda function + list comprehension
In this method, we define a lambda function that takes a matrix as input and uses a list comprehension to print the maximum element of each row using the NumPy max() function.
Note: Before using numpy you first need to install it by using the following command: pip install numpy
Below is the code for the following method:
Python3
import
numpy as np
maxelement
=
lambda
arr: [
print
(np.
max
(row), end
=
" "
)
for
row
in
arr]
arr
=
[[
3
,
4
,
1
,
8
],
[
1
,
4
,
9
,
11
],
[
76
,
34
,
21
,
1
],
[
2
,
1
,
4
,
5
]]
maxelement(arr)
Output:
Time complexity: O(n*m), where n is the number of rows and m is the number of columns in the matrix.
Auxiliary Space: O(1)
Please refer complete article on Find maximum element of each row in a matrix for more details!
Last Updated :
29 Mar, 2023
Like Article
Save Article
30 / 25 / 5
Регистрация: 05.08.2021
Сообщений: 83
08.06.2022, 06:25
9
Python | ||
|
Результат:
[2, 3, 0, 5]
[0, 0, 0, 0]
[2, 3, 0, 5]
[1, 1, 0, 1]
0
In this article, we will learn a python program to find the maximum element of each row in a matrix.
Assume we have taken an NxN input matrix. We will now find the maximum element of each row in an input matrix using the below methods.
Methos Used
The following are the various methods to accomplish this task −
-
Using Nested For Loops
-
Using max() function
-
Using map(),lambda functions
Method 1: Using Nested For Loops
Algorithm (Steps)
Following are the Algorithm/steps to be followed to perform the desired task. −
-
Create a function maximumRowElement() to print the maximum element of each row of an input matrix by accepting the input matrix as an argument.
-
Get the number of rows of the matrix by calculating the length of the matrix using the len() function.
-
Get the number of columns of the matrix by calculating the length of any row of the matrix.
-
Traverse through the rows of the matrix using for loop
-
Take a variable to store the maximum row element and initialize it to 0.
-
Traverse through all the columns of a matrix using another nested for loop.
-
Check whether the current element value is greater than the above max variable.
-
If the above condition is true then set this element as the maximum value.
-
Print the maximum value variable.
-
Create a variable to store the input matrix and print the given matrix using nested for loops.
-
Call the above-defined maximumRowElement() function by passing the input matrix as an argument to print the maximum element of each row in a matrix.
Example
The following program returns the maximum element of each row of an input matrix using the nested for loop −
# creatind a function to get the maximum element in a # row of a matrix by accepting the input matrix as an argument def maximumRowElement(inputMatrix): # getting the number of rows of the given matrix rows = len(inputMatrix) # getting the number of columns of the given matrix cols = len(inputMatrix[0]) # traversing through the rows of the matrix for p in range(rows): # initializing maximum with 0 for finding a maximum element of each row maximum = 0 # traversing through all the columns of a matrix for q in range(cols): # checking whether the current element value is greater than the max value if inputMatrix[p][q] > maximum: # assigning that element to the maximum now it becomes the maximum element maximum = inputMatrix[p][q] # printing the maximum element of each row of a matrix print(maximum) # input matrix(3x3 matrix) inputMatrix = [[5, 1, 3, 4], [6, 10, 8, 11], [7, 2, 4, 3], [1, 2, 3, 4]] print("The Given Matrix is:") # traversing through the rows of a matrix for m in range(len(inputMatrix)): # traversing through all the columns of the current row for n in range(len(inputMatrix[0])): # printing the corresponding element print(inputMatrix[m][n], end=' ') print() print("maximum element in each row of an input matrix is:") # calling the maximumRowElement() function by passing # input matrix to it maximumRowElement(inputMatrix)
Output
On executing, the above program will generate the following output −
The Given Matrix is: 5 1 3 4 6 10 8 11 7 2 4 3 1 2 3 4 maximum element in each row of an input matrix is: 5 11 7 4
Method 2: Using max() Function
The max() method(returns the highest-valued item/greatest numbers in an iterable)
Example
The following program returns the maximum element of each row of an input matrix using the max() function −
# input matrix(3x3 matrix) inputMatrix = [[5, 1, 3, 4], [6, 10, 8, 11], [7, 2, 4, 3], [1, 2, 3, 4]] print("The Given Matrix is:") # traversing through the rows of a matrix for m in range(len(inputMatrix)): for n in range(len(inputMatrix[0])): # printing the corresponding element print(inputMatrix[m][n], end=' ') print() print("maximum element in each row of an input matrix is:") # traversing through each row of elements of the matrix for k in inputMatrix: # printing the maximum element in a row using the max() function print(max(k))
Output
The Given Matrix is: 5 1 3 4 6 10 8 11 7 2 4 3 1 2 3 4 maximum element in each row of an input matrix is: 5 11 7 4
Method 3: Using map(), Lambda Functions
Using the built-in map() function is another method that can be used to get the largest element in each row of a matrix. The map() method applies a specified function on each element of an iterable in a definite way (such as a list or a matrix). The map() method may be used in this situation to apply the max() function to each row of the matrix.
Example
The following program returns the maximum element of each row of an input matrix using the map(),lambda functions −
# input matrix(3x3 matrix) inputMatrix = [[5, 1, 3, 4], [6, 10, 8, 11], [7, 2, 4, 3], [1, 2, 3, 4]] print("The Given Matrix is:") # traversing through the rows of a matrix for m in range(len(inputMatrix)): # traversing through all the columns of the current row for n in range(len(inputMatrix[0])): # printing the corresponding element print(inputMatrix[m][n], end=' ') print() print("maximum element in each row of an input matrix is:") # Applying max() function to each list element(row) to get maximum value result = list(map(lambda row: max(row), inputMatrix)) # Traversing in the result list for i in result: # Printing the maximum row element print(i)
Output
The Given Matrix is: 5 1 3 4 6 10 8 11 7 2 4 3 1 2 3 4 maximum element in each row of an input matrix is: 5 11 7 4
Conclusion
In this article, we learned three different approaches of printing each row’s highest value in the given matrix. We also learned how to apply a certain condition to each iterable using the map() function.
Матрица — это двумерный массив, состоящий из M строк и N столбцов. Матрицы часто используются в математических вычислениях. Программисты работают с матрицами в основном в научной области, однако их можно использовать и для других вещей, например, для быстрой генерации уровней в видео-игре.
Матрицы и библиотека NumPy
Программист может самостоятельно реализовать все функции для работы с матрицами: умножение, сложение, транспонирование и т. д. На Python это сделать гораздо проще, чем на более низкоуровневых языках, таких как C.
Но каждый раз писать одни и те же алгоритмы не имеет смысла, поэтому была разработана библиотека NumPy. Она используется для сложных научных вычислений и предоставляет программисту функции для работы с двумерными массивами.
Вместо того чтобы писать десятки строк кода для выполнения простых операций над матрицами, программист может использовать одну функцию из NumPy. Библиотека написана на Python, C и Фортране, поэтому функции работают даже быстрее, чем на чистом Python.
Подключение библиотеки NumPy
NumPy не встроена в интерпретатор Python, поэтому перед импортом её необходимо установить. Для этого в можно воспользоваться утилитой pip. Введите в консоле команду:
pip install numpy
Теперь, когда библиотека установлена, её можно подключить с помощью команды import
. Для удобства переименуем numpy
при импорте в np
следующим образом:
import numpy as np
Ниже в примерах будет использован именно такой импорт, поэтому обращение к библиотеке будет через np
, а не numpy
!
Создание
Для создании матрицы используется функция array(). В функцию передаётся список. Вот пример создания, мы подаём в качестве аргумента функции двумерный список:
a = np.array([[3, 3, 3], [2, 5, 5]])
Вторым параметром можно задать тип элементов матрицы:
a = np.array([[3, 3, 3],[2, 5, 5]], int) print(a)
Тогда в консоль выведется:
[[3 3 3] [2 5 5]]
Обратите внимание, что если изменить int на str, то тип элементов изменился на строковый. Кроме того, при выводе в консоль NumPy автоматически отформатировал вывод, чтобы он выглядел как матрица, а элементы располагались друг под другом.
В качестве типов элементов можно использовать int, float, bool, complex, bytes, str, buffers. Также можно использовать и другие типы NumPy: логические, целочисленные, беззнаковые целочисленные, вещественные, комплексные. Вот несколько примеров:
- np.bool8 — логическая переменная, которая занимает 1 байт памяти.
- np.int64 — целое число, занимающее 8 байт.
- np.uint16 — беззнаковое целое число, занимающее 2 байта в памяти.
- np.float32 — вещественное число, занимающее 4 байта в памяти.
- np.complex64 — комплексное число, состоящее из 4 байтового вещественного числа действительной части и 4 байтов мнимой.
Вы также можете узнать размер матрицы, для этого используйте атрибут shape:
size = a.shape print(size) # Выведет (2, 3)
Первое число (2) — количество строк, второе число (3) — количество столбцов.
Нулевая матрица
Если необходимо создать матрицу, состоящую только из нулей, используйте функцию zeros():
a_of_zeros = np.zeros((2,2)) print(a_of_zeros)
Результат этого кода будет следующий:
[[0. 0.] [0. 0.]]
Получение строки, столбца и элемента
Чтобы получить строку двухмерной матрицы, нужно просто обратиться к ней по индексу следующим образом:
temp = a[0] print(temp) #Выведет [3 3 3]
Получить столбец уже не так просто. Используем срезы, в качестве первого элемента среза мы ничего не указываем, а второй элемент — это номер искомого столбца. Пример:
arr = np.array([[3,3,3],[2,5,5]], str) temp = arr[:,2] print(temp) # Выведет ['3' '5']
Чтобы получить элемент, нужно указать номер столбца и строки, в которых он находится. Например, элемент во 2 строке и 3 столбце — это 5, проверяем (помним, что нумерация начинается с 0):
arr = np.array([[3,3,3],[2,5,5]], str) temp = arr[1][2] print(temp) # Выведет 5
Умножение и сложение
Чтобы сложить матрицы, нужно сложить все их соответствующие элементы. В Python для их сложения используется обычный оператор «+».
Пример сложения:
arr1 = np.array([[3,3,3],[2,5,5]]) arr2 = np.array([[2,4,2],[1,3,8]]) temp = arr1 + arr2 print(temp)
Результирующая матрица будет равна:
[[ 5 7 5] [ 3 8 13]]
Важно помнить, что складывать можно только матрицы с одинаковым количеством строк и столбцов, иначе программа на Python завершится с исключением ValueError.
Умножение матриц сильно отличается от сложения. Не получится просто перемножить соответствующие элементы двух матриц. Во-первых, матрицы должны быть согласованными, то есть количество столбцов одной должно быть равно количеству строк другой и наоборот, иначе программа вызовет ошибку.
Умножение в NumPy выполняется с помощью метода dot().
Пример умножения:
arr1 = np.array([[3,3],[2,5]]) arr2 = np.array([[2,4],[1,3]]) temp = arr1.dot(arr2) print(temp)
Результат выполнения этого кода будет следующий:
[[ 9 21] [ 9 23]]
Как она получилась? Разберём число 21, его позиция это 1 строка и 2 столбец, тогда мы берем 1 строку первой матрицы и умножаем на 2 столбец второй. Причём элементы умножаются позиционно, то есть 1 на 1 и 2 на 2, а результаты складываются: [3,3] * [4,3] = 3 * 4 + 3 * 3 = 21.
Транспонированная и обратная
Транспонированная матрица — это матрица, у которой строки и столбцы поменялись местами. В библиотеки NumPy для транспонирования двумерных матриц используется метод transpose(). Пример:
arr1 = np.array([[3,3],[2,5]]) temp = arr1.transpose() print(temp)
В результате получится матрица:
[[3 2] [3 5]]
Чтобы получить обратную матрицу, необходимо использовать модуль linalg (линейная алгебра). Используем функцию inv():
arr1 = np.array([[3,3],[2,5]]) temp = np.linalg.inv(arr1) print(temp)
Результирующая матрица будет равна:
[[ 0.55555556 -0.33333333] [-0.22222222 0.33333333]]
Получение максимального и минимального элемента
Чтобы получить максимальный или минимальный элемент, можно пройтись по всем элементам матрицы с помощью двух циклов for
. Это стандартный алгоритм перебора, который известен почти каждому программисту:
arr = np.array([[3,3],[2,5]]) min = arr[0][0] for i in range(arr.shape[0]): for j in range(arr.shape[1]): if min > arr[i][j]: min = arr[i][j] print("Минимальный элемент:", min) # Выведет "Минимальный элемент: 2"
NumPy позволяет найти максимальный и минимальный элемент с помощью функций amax() и amin(). В качестве аргумента в функции нужно передать саму матрицу. Пример:
arr1 = np.array([[3,3],[2,5]]) min = np.amin(arr1) max = np.amax(arr1) print("Минимальный элемент:", min) # Выведет "Минимальный элемент: 2" print("Максимальный элемент:", max) # Выведет "Максимальный элемент: 5"
Как видим, результаты реализации на чистом Python и реализации с использованием библиотеки NumPy совпадают.
Заключение
На Python можно реализовать все необходимые функции для работы с матрицами. Чтобы упростить работу программистов, была создана библиотека NumPy. Она позволяет производить сложные математические вычисления легко и без ошибок, избавляя программиста от необходимости каждый раз писать один и тот же код.