【问题标题】:Accessing the nth element of a matrix访问矩阵的第 n 个元素
【发布时间】:2020-09-06 14:33:42
【问题描述】:

给定一个数字 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]
]

【问题讨论】:

  • 您的示例中的输出是什么?
  • 没有输出,这是一个理论问题
  • 那么应该是 $a_7$
  • 你的 array of arrays 的行是否总是等长?
  • 是的,他们会的

标签: arrays matrix search modulus


【解决方案1】:

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

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

【讨论】:

  • 可能 / 应该是 // 或强制转换为 int
  • 除法应该是基于整数的(这样忽略任何非零余数),是的。例如:3 / 4 = 06 / 4 = 1
【解决方案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")

【讨论】:

  • OP 不是在矩阵中搜索 value n,而是在 index n 处的元素。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多