You can also add a tag to your function to search the occurrences of your input matrix/list.
For example:
If you input is 1D vector:
def get_index_1d(a = [], val = 0, occurrence_pos = False):
if not occurrence_pos:
for k in range(len(a)):
if a[k] == val:
return k
else:
return [k for k in range(len(a)) if a[k] == val]
Output:
a = [1,10,54,85, 10]
index = get_index_1d(a, 10, False)
print("Without occurrence: ", index)
index = get_index_1d(a, 10, True)
print("With occurrence: ", index)
>>> Without occurrence: 1
>>> With occurrence: [1, 4]
For 2D vector:
def get_index_2d(a = [], val = 0, occurrence_pos = False):
if not occurrence_pos:
for k in range(len(a)):
for j in range(len(a[k])):
if a[k][j] == val:
return (k, j)
else:
return [(k, j) for k in range(len(a)) for j in range(len(a[k])) if a[k][j] == val]
Output:
b = [[1,2],[3,4],[5,6], [3,7]]
index = get_index_2d(b, 3, False)
print("Without occurrence: ", index)
index = get_index_2d(b, 3, True)
print("With occurrence: ", index)
>>> Without occurrence: (1, 0)
>>> With occurrence: [(1, 0), (3, 0)]
This is a benchmark of all the answers posted so far including two of my own. I think you may find the results useful, enlightening, and maybe even surprising. ;¬)
Note I’ve put the target value to middle of matrix to simulate its average location if the data are random in an effort to level the playing field (a little bit) for algorithms that stop as soon it’s is found — the comparison still isn’t really fair, however.
Runs under both Python 2 & 3.
Update — Added answers that have been posted after last update to this one.
from __future__ import print_function
import numpy as np
import sys
from textwrap import dedent
import timeit
EXECUTIONS = 1000000 # Number of times each algorithm is executed per timing run.
TIMINGS = 3 # Number of timing runs.
SETUP = dedent("""
# Make accessible in algorithms.
from __main__ import np
mymatrix=[[1,2,3], [4,9,6], [7,8,5]] # Target value in middle.
val = 9 # Target value.
""")
algorithms = {
"user2459905 (OP) - all occurrences": dedent("""
# finds all occurrences
found = []
for i,j in enumerate(mymatrix):
for k,l in enumerate(j):
if l==val:
found.append((i,k))
"""),
"ayush thakur (fixed) - all occurrences": dedent("""
# finds all occurrences
found = []
for i, e in enumerate(mymatrix):
for j, ee in enumerate(e):
if val == ee: # Fixed.
found.append((i, j))
"""),
"martineau #1 - all occurrences": dedent("""
# finds all occurrences
width = len(mymatrix[0])
found = []
posn = 0
for row in mymatrix:
if val not in row:
posn += width
else:
for col in row:
if col == val:
found.append((posn // width, posn % width))
posn += 1
"""),
"martineau #2 - all occurrences": dedent("""
# finds all occurrences
width = len(mymatrix[0])
found = []
posn = 0
for row in mymatrix:
if val in row:
for y,col in enumerate(row):
if col == val:
found.append((posn // width, y))
posn += width
"""),
"mmtauqir - first occurrence": dedent("""
# finds all occurrences
matrix_dim = len(mymatrix[0])
item_index = 0
for row in mymatrix:
for i in row:
if i == val:
break
item_index += 1
if i == val:
break
found = (int(item_index / matrix_dim), item_index % matrix_dim)
"""),
"rtrwalker - all occurrences using numpy": dedent("""
# finds all occurrences using numpy
a = np.array(mymatrix) # Convert mymatrix to a numpy array.
found = np.where(a==val)
"""),
"Ryan Haining - first occurrence (per row)": dedent("""
# finds first occurrence in each row
found = [(index, row.index(val)) for index, row in enumerate(mymatrix)
if val in row]
"""),
}
# Benchmark algorithms
timings = [
(label, min(timeit.repeat(algorithms[label], setup=SETUP,
repeat=TIMINGS, number=EXECUTIONS)))
for label in algorithms
]
# Display metrics.
longest = max(len(timing[0]) for timing in timings) # Length of longest label.
print('Fastest to slowest execution speeds with {}-bit Python {}.{}.{}'.format(
64 if sys.maxsize > 2**32 else 32, *sys.version_info[:3]))
print(' with numpy version {}'.format(np.version.full_version),
'-> {:,d} executions, best of {:,d})'.format(EXECUTIONS, TIMINGS))
print()
ranked = sorted(timings, key=lambda t: t[1]) # sort by speed (fastest first)
for timing in ranked:
print("{:>{width}} : {:.6f} secs, rel speed {rel:6.3f}x".format(
timing[0], timing[1], rel=timing[1]/ranked[0][1], width=longest))
Results:
Fastest to slowest execution speeds with 32-bit Python 2.7.18
with numpy version 1.16.6 -> 1,000,000 executions, best of 3)
mmtauqir - first occurrence : 0.667560 secs, rel speed 1.000x
Ryan Haining - first occurrence (per row) : 0.694786 secs, rel speed 1.041x
martineau #1 - all occurrences : 0.752011 secs, rel speed 1.127x
martineau #2 - all occurrences : 0.929674 secs, rel speed 1.393x
ayush thakur (fixed) - all occurrences : 1.541785 secs, rel speed 2.310x
user2459905 (OP) - all occurrences : 1.544341 secs, rel speed 2.313x
rtrwalker - all occurrences using numpy : 3.334727 secs, rel speed 4.995x
Fastest to slowest execution speeds with 32-bit Python 3.8.8
with numpy version 1.21.1 -> 1,000,000 executions, best of 3)
mmtauqir - first occurrence : 0.734707 secs, rel speed 1.000x
Ryan Haining - first occurrence (per row) : 0.749999 secs, rel speed 1.021x
martineau #2 - all occurrences : 0.820354 secs, rel speed 1.117x
martineau #1 - all occurrences : 0.880883 secs, rel speed 1.199x
user2459905 (OP) - all occurrences : 1.436644 secs, rel speed 1.955x
ayush thakur (fixed) - all occurrences : 1.638413 secs, rel speed 2.230x
rtrwalker - all occurrences using numpy : 5.713464 secs, rel speed 7.777x
Python supports a list as its list element and hence a matrix can be formed. Sometimes we might have a utility in which we require to perform a search in that list of list i.e matrix and its a very common in all the domains of coding. Let’s discuss certain ways in which this can be performed.
Method #1 : Using any() + list comprehension The any function can be used to perform the task of if condition and the check for each element in the nested list can be computed using the list comprehension.
Python3
test_list
=
[[
4
,
5
,
6
],
[
10
,
2
,
13
],
[
1
,
11
,
18
]]
print
("The original
list
: "
+
str
(test_list))
res
=
any
(
13
in
sub
for
sub
in
test_list)
print
("Is
13
present
in
Matrix ? : "
+
str
(res))
Output :
The original list : [[4, 5, 6], [10, 2, 13], [1, 11, 18]] Is 13 present in Matrix ? : True
Method #2 : Using set.issubset() + itertools.chain() The issubset method can be used to check for the membership in sublist and chain function can be used to perform this task for the each element in the Matrix, in a faster way as it works on iterators.
Python3
from
itertools
import
chain
test_list
=
[[
4
,
5
,
6
],
[
10
,
2
,
13
],
[
1
,
11
,
18
]]
print
("The original
list
: "
+
str
(test_list))
res
=
{
13
}.issubset(chain.from_iterable(test_list))
print
("Is
13
present
in
Matrix ? : "
+
str
(res))
Output :
The original list : [[4, 5, 6], [10, 2, 13], [1, 11, 18]] Is 13 present in Matrix ? : True
Method #3 : Using Counter() function
Python3
from
collections
import
Counter
test_list
=
[[
4
,
5
,
6
],
[
10
,
2
,
13
],
[
1
,
11
,
18
]]
print
(
"The original list : "
+
str
(test_list))
res
=
False
matrixElements
=
[]
for
i
in
test_list:
matrixElements.extend(i)
freq
=
Counter(matrixElements)
if
13
in
freq.keys():
res
=
True
print
(
"Is 13 present in Matrix ? : "
+
str
(res))
Output
The original list : [[4, 5, 6], [10, 2, 13], [1, 11, 18]] Is 13 present in Matrix ? : True
Time Complexity:O(N*N)
Auxiliary Space: O(N*N)
Method #4:Using reduce()
1. Set the flag variable res to False
2. Initialize an empty list matrixElements
3. For each row in matrix, do the following:
a. Append each element of the row to matrixElements
4. Check if the target element is in matrixElements:
a. If it is, set res to True
5. Return the value of res as the result
Python3
from
functools
import
reduce
test_list
=
[[
4
,
5
,
6
],
[
10
,
2
,
13
],
[
1
,
11
,
18
]]
print
(
"The original list : "
+
str
(test_list))
res
=
False
matrixElements
=
reduce
(
lambda
x, y: x
+
y, test_list)
if
13
in
matrixElements:
res
=
True
print
(
"Is 13 present in Matrix ? : "
+
str
(res))
Output
The original list : [[4, 5, 6], [10, 2, 13], [1, 11, 18]] Is 13 present in Matrix ? : True
The time complexity of the algorithm for searching an element in a matrix using the Counter module or reduce function is O(mn), where m is the number of rows and n is the number of columns in the matrix.
The space complexity of the algorithm is also O(mn), since we are flattening the matrix into a 1D list that contains all the elements of the matrix. This list requires space proportional to the total number of elements in the matrix.
Method #5: Using numpy:
Algorithm:
- Initialize a list of lists (matrix) with the given elements.
- Use the numpy isin function to check if the given element (13 in this case) is present in the matrix.
- Use the any function on the resulting boolean array to check if at least one True value exists.
- Print the result.
Python3
import
numpy as np
test_list
=
[[
4
,
5
,
6
],
[
10
,
2
,
13
],
[
1
,
11
,
18
]]
print
(
"The original list : "
+
str
(test_list))
res
=
np.isin(test_list,
13
).
any
()
print
(
"Is 13 present in Matrix ? : "
+
str
(res))
Output: The original list : [[4, 5, 6], [10, 2, 13], [1, 11, 18]] Is 13 present in Matrix ? : True
Time Complexity:
The time complexity of this code is O(m*n), where m and n are the dimensions of the matrix. The numpy isin function has a linear time complexity.
Auxiliary Space:
The space complexity of this code is O(mn), where m and n are the dimensions of the matrix. This is because the numpy array created to store the matrix elements takes up O(mn) space.
Using numpy.where to search elements in a Matrix:
Algorithm:
Convert the matrix into a numpy array using numpy.array()
Use numpy.where() to get the indices where the target element is present
Convert the indices into a list using tolist() method
Print the result in the desired format
Python3
import
numpy as np
test_list
=
[[
4
,
5
,
6
],
[
10
,
2
,
13
],
[
1
,
11
,
18
]]
print
(
"The original list : "
+
str
(test_list))
matrix
=
np.array(test_list)
target
=
13
indices
=
np.argwhere(matrix
=
=
target).tolist()
if
len
(indices) >
0
:
print
(f
"Is {target} present in Matrix ? : True"
)
else
:
print
(f
"Is {target} present in Matrix ? : False"
)
Output:
The original list : [[4, 5, 6], [10, 2, 13], [1, 11, 18]]
Is 13 present in Matrix ? : True
Time Complexity: O(m*n), where m is the number of rows and n is the number of columns in the matrix. This is because we need to traverse the entire matrix to find the target element.
Auxiliary Space: O(m*n), as we are converting the matrix into a numpy array and creating a list of indices where the target element is present. The space used by numpy is proportional to the number of elements in the matrix.
Last Updated :
02 May, 2023
Like Article
Save Article
[ тот самый код ]
def count_neighbours(grid, row, col): # [row] - ряд
# [col] - столбец
mass_el_1 = []
grid1 = np.array(grid)
mass8 = [(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)]
mass3 = [(0,4),(4,4),(4,0),(0,0)]
mass5 = [(1,0),(2,0),(3,0),(0,1),(0,2),(0,3),(1,4),(2,4),(3,4),(4,1),(4,2),(4,3)]
xl = []
yl = []
for x in range(grid1.shape[0]):
for y in range(grid1.shape[1]):
if grid1[x, y] != 0:
print (x, y)
xl.append(x)
yl.append(y)
print(xl)
print(yl)
listindex = list(zip(xl,yl))
print(listindex)
xlll = []
ylll = []
neighbours = []
exepts = []
for x in range(grid1.shape[0]):
for y in range(grid1.shape[1]):
if grid1[x, y] != 0:
for i in listindex:
print('i: ',i)
for i1 in mass8:
print('i1: ',i1)
if i == i1:
try:
if grid1[x-1, y-1] == 1:
neighbours.append((x-1, y-1))
elif grid1[x, y-1] == 1:
neighbours.append((x, y-1))
elif grid1[x+1, y-1] == 1:
neighbours.append((x+1, y-1))
elif grid1[x+1, y] == 1:
neighbours.append((x+1, y))
elif grid1[x+1, y+1] == 1:
neighbours.append((x+1, y+1))
elif grid1[x, y+1] == 1:
neighbours.append((x, y+1))
elif grid1[x-1, y+1] == 1:
neighbours.append((x-1, y+1))
elif grid1[x-1, y] == 1:
neighbours.append((x-1, y))
except IndexError :
exepts.append((x,y))
print(neighbours,"len:",len(neighbours))
print(exepts,"len:",len(exepts))
count_neighbours(((1, 0, 0, 1, 0),
(0, 1, 0, 0, 0),
(0, 0, 1, 0, 1),
(1, 0, 0, 0, 0),
(0, 0, 1, 0, 0),),0,0)
На уроке рассматриваются алгоритмы работы с двумерными массивами в Python: создание матрицы, инициализация элементов, вывод, обработка элементов матрицы
Создание, вывод и ввод матрицы в Питоне
- Таким образом, получается структура из вложенных списков, количество которых определяет количество строк матрицы, а число элементов внутри каждого вложенного списка указывает на количество столбцов в исходной матрице.
- Вывод матрицы можно осуществить одним оператором, но такой простой способ не позволяет выполнять какой-то предварительной обработки элементов:
Для работы с матрицами в Python также используются списки. Каждый элемент списка-матрицы содержит вложенный список.
Рассмотрим пример матрицы размера 4 х 3:
matrix = [[-1, 0, 1], [-1, 0, 1], [0, 1, -1], [1, 1, -1]]
Данный оператор можно записать в одну строку:
matrix = [[-1, 0, 1], [-1, 0, 1], [0, 1, -1], [1, 1, -1]]
Результат:
- способ:
- способ:
1 2 3 4 5 |
def printMatrix ( matrix ): for i in range ( len(matrix) ): for j in range ( len(matrix[i]) ): print ( "{:4d}".format(matrix[i][j]), end = "" ) print () |
В примере i – это номер строки, а j – номер столбца;
len(matrix) – число строк в матрице.
1 2 3 4 5 |
def printMatrix ( matrix ): for row in matrix: for x in row: print ( "{:4d}".format(x), end = "" ) print () |
Внешний цикл проходит по строкам матрицы (row), а внутренний цикл проходит по элементам каждой строки (x).
1 2 3 4 |
from random import randint n, m = 3, 3 a = [[randint(1, 10) for j in range(m)] for i in range(n)] print(a) |
Обработка элементов двумерного массива
Нумерация элементов двумерного массива, как и элементов одномерного массива, начинается с нуля.
Т.е. matrix[2][3]
— это элемент третьей строки четвертого столбца.
Пример обработки элементов матрицы:
Найти произведение элементов двумерного массива.
✍ Решение:
1 2 3 4 5 |
p = 1 for i in range(N): for j in range(M): p *= matrix[i][j] print (p) |
Пример:
Найти сумму элементов двумерного массива.
✍ Решение:
Более подходящий вариант для Python:
1 2 3 4 |
s = 0 for row in matrix: s += sum(row) print (s) |
Для поиска суммы существует стандартная функция sum.
Задание Python 8_0:
Получены значения температуры воздуха за 4 дня с трех метеостанций, расположенных в разных регионах страны:
Номер станции | 1-й день | 2-й день | 3-й день | 4-й день |
---|---|---|---|---|
1 | -8 | -14 | -19 | -18 |
2 | 25 | 28 | 26 | 20 |
3 | 11 | 18 | 20 | 25 |
Т.е. запись показаний в двумерном массиве выглядела бы так:
t[0][0]=-8 | t[0][1]=-14 | t[0][2]=-19 | t[0][3]=-18 |
t[1][0]=25 | t[1][1]=28 | t[1][2]=26 | t[1][3]=20 |
t[2][0]=11 | t[2][1]=18 | t[2][2]=20 | t[2][3]=25 |
- Распечатать температуру на 2-й метеостанции за 4-й день и на 3-й метеостанции за 1-й день.
- Распечатать показания термометров всех метеостанций за 2-й день.
- Определить среднюю температуру на 3-й метеостанции.
- Распечатать, в какие дни и на каких метеостанциях температура была в диапазоне 24-26 градусов тепла.
Задание Python 8_1:
Написать программу поиска минимального и максимального элементов матрицы и их индексов.
Задание Python 8_2:
Написать программу, выводящую на экран строку матрицы, сумма элементов которой максимальна.
for i in range(N): # работаем с matrix[i][i]
for i in range(N): # работаем с matrix[i][N-1-i]
Пример:Переставить 2-й и 4-й столбцы матрицы. Использовать два способа.
✍ Решение:
for i in range(N): c = A[i][2] A[i][2] = A[i][4] A[i][4] = c
for i in range(N): A[i][2], A[i][4] = A[i][4], A[i][2]
Задание Python 8_3:
Составить программу, позволяющую с помощью датчика случайных чисел сформировать матрицу размерностью N. Определить: