二叉树搜索未排序的矩阵?

2024-10-01 02:21:57 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法用二叉树搜索未排序的矩阵?如果是的话,你能解释一下吗?因为我是编程新手?我曾经尝试过使用嵌套的for i for jfor循环来实现它,但不知道是否有更快的方法

import numpy as np

matrix = [[3, 6, 7], [9, 1, 2], [8, 4, 5]] 
matrix = np.array(matrix)  
matrix
array([[3, 6, 7],
       [9, 1, 2],
       [8, 4, 5]]) # how does one perform a binary tree search on an unsorted matrix?

Tags: 方法importnumpyfor排序as编程np
1条回答
网友
1楼 · 发布于 2024-10-01 02:21:57

您可以使用np.where进行此操作

matrix = np.array([[3,6,7],[9,1,2],[8, 8, 8]])
dim_1, dim_2 = np.where(matrix == 8)
#dim_1 = array([2, 2, 2], dtype=int64)
#dim_2 = array([0, 1, 2], dtype=int64)
#dim_1, dim_2, dim_3 = np.where(matrix == 8) if matrix had shape (3, )
num_8 = len(ret[0]) #total number of 8's

np.where返回数组元组,数组元组由基于数组形状的索引分隔。如果您有一个3D数组,那么元组中将有3个数组。 ret = (array([2, 2, 2], dtype=int64), array([0, 1, 2], dtype=int64))ret[0]对应于行值,ret[1]对应于列值。 这意味着元素8存在于matrix[2][0]matrix[2][1]matrix[2][2]

这有用吗?你不必为此编写自己的例程。非常肯定,这将比在纯python中实现的任何搜索例程都要快,因为NumPy内置函数经过了高度优化。在可能的情况下,您应该考虑使用NUMPY方法对NUMPY数组。

相关问题 更多 >