-1

I began with python and I need to find, in a matrix, the next higher number from a given number. Actually the value of the number is not interesting but I need its location.

For example, if my matrix is

a = ([0.14, 0.93, 0.2], [0.1, 0.8, 0.55])

and my given number is 0.5

How would I do to have (3, 2) for i and j value of 0.55 which is the next higher number from 0.5?

4

3 回答 3

1

您可以以扁平的方式遍历单元格:

>>> a = ([0.14,0.93,0.2],[0.1,0.8,0.55])
>>> [(v, (j, i)) for i, row in enumerate(a,1) for j,v in enumerate(row, 1)]
[(0.14, (1, 1)), (0.93, (2, 1)), (0.2, (3, 1)), (0.1, (1, 2)), (0.8, (2, 2)), (0.55, (3, 2))]

由于您还想要 > 0.5 的最小元素,我们可以这样做:

>>> cc = ((v, (j, i)) for i, row in enumerate(a,1) for j,v in enumerate(row, 1))
>>> min(c for c in cc if c[0] > 0.5)
(0.55, (3, 2))

(我们可以将所有这些都塞进一行,但我认为将枚举与搜索分开会更清楚。)

于 2013-04-06T20:36:09.350 回答
0

这取决于您是需要先按列搜索还是按行搜索。无论哪种方式,您都可以对行或列进行排序。这样您就可以对每一行/列执行二进制搜索。

于 2013-04-06T20:29:55.467 回答
0

恐怕您需要扫描矩阵中的每个元素...

代码看起来像这样:

num=0.5
min = 999.999 # or a large enough number
pos_i=-1
pos_j=-1

for i ...:
    for j ...:
        if a[i][j] < min and a[i][j] > num:
            pos_i = i
            pos_j = j
            min = a[i][j]

这具有 O(n^2) 复杂度

您可以通过对数据进行排序来改进,大约 O(n log(n)),但这取决于您是否要保留索引...

于 2013-04-06T20:35:51.400 回答