在矩阵中查找第一列,其中所有元素都是正数。上一列元素的符号发生了变化。
例如:在矩阵中,第2列包含所有正元素。
matrix = [[-5, -6, 2], [7, 2, 1], [8, -4, 9]]
然后上一栏改变了标志。
matrix = [[-5, 6, 2], [7, -2, 1], [8, 4, 9]]
答案 0 :(得分:1)
matrix = [[-5, -6, 2], [7, 2, 1], [8, -4, 9]]
# column is positive until proven negativity.
results = [True, True, True]
# We loop over the rows...
for row in matrix:
# And we loop over all the items in the row...
for index,item in enumerate(row):
# If the element is negative, item > 0 will be False, and this way results[index] will be set as False and will be True no more.
results[index] = results[index] and (item > 0)
for index2,result in enumerate(results):
if result:
print "The {0} column is positive".format(index2)
# Calculate the previous columns
previous = index2 - 1
# We invert the sign of the position 'previous' of every row.
for row in matrix:
row[previous] = - row[previous]
break
运行脚本后,结果列表应该是这样的
print results
[False, False, True]
这意味着最后一列是正面的。
答案 1 :(得分:0)
我不太了解python,所以我用C ++代码编写
int previous_col = 0;
int row_count = 0;
for (int col = 0; col < columns; ++col)
{
for (int row = 0; row < rows; ++row)
{
if (matrix[row][col] >= 0)
++row_count;
}
if (row_count = rows)
{
col - 1 < 0 ? columns - 1 : col - 1;
for (int row = 0; row < rows; ++row)
{
matrix[row][col] *= -1;
}
break;
}
}
答案 2 :(得分:0)
你有可用的numpy吗?它是为这些操作而制作的,允许您编写更简洁和矢量化的代码。
import numpy as np
A = np.array(matrix)
In [21]: A
Out[21]:
array([[-5, -6, 2],
[ 7, 2, 1],
[ 8, -4, 9]])
ix = np.argmax((A >= 0).all(axis=0))
如果第一个非负列为0,则使用模数超过列数
prev_ix = (ix - 1) % A.shape[1]
A[:, prev_ix] *= -1
In [24]: A
Out[24]:
array([[-5, 6, 2],
[ 7, -2, 1],
[ 8, 4, 9]])
你实际上可以将所有这些操作都填充到一个内容中,尽管可读性稍差:)
A[:, ((np.argmax((A >= 0).all(axis=0)) - 1) % A.shape[1])] *= 1