访问矩阵的第n个元素

问题描述 投票:1回答:2

给定一个数字n和一个矩阵,用数组表示。你将如何找到第n个元素?我所寻找的答案应该涉及模数运算,而不是使用标准库函数。

所以例如n=7和矩阵。

[
[a_1,a_2,a_3,a_4],
[a_5,a_6,a_7,a_8],
[a_9,a_10,a_11,a_12]
]
arrays matrix search modulus
2个回答
1
投票

假设我们使用基于零的索引来使事情变得更简单。所以,如果我们想要第7个元素,我们使用的是 n=6.

rowIndex = n / rowLength
columnIndex = n % rowLength
answer = array[rowIndex][columnIndex]

-2
投票

希望这能帮助你。

############# Inputs ################

matrix = [[1,2,3],
         [4,5,6]]
## n is the element we need to find 
n = 16

########## Search Matrix element Logic ###########

for i in range(len(matrix)):
    for j in range(len(matrix[1])):
        if matrix[i][j] == n:
            print('row:',i,' column:',j)
            break;

        elif ( (j == len(matrix[1])-1)  and (i== len(matrix)-1) ):
            print("element not found")
© www.soinside.com 2019 - 2024. All rights reserved.