Python 计算逐列和逐行排序的矩阵中的负数个数
在这个示例中,我们将计算逐列和逐行排序的矩阵中的负数个数。首先,我们将创建一个矩阵−
mat = [
[-1, 3, 5, 7],
[-6, -3, 1, 4],
[-5, -1, -10, 12]
]
将矩阵传递给自定义函数,并使用嵌套的for循环 –
def negativeFunc(mat, r, c):
count = 0
for i in range(r):
for j in range(c):
if mat[i][j] < 0:
count += 1
else:
break
return count
上面,在for循环中检查每个矩阵元素是否为负数。 当找到负值时,计数会递增。
这是完整的示例−
示例
# The matrix must be sorted in ascending order, else it won't work
def negativeFunc(mat, r, c):
count = 0
for i in range(r):
for j in range(c):
if mat[i][j] < 0:
count += 1
else:
break
return count
# Driver code
mat = [
[-1, 3, 5, 7],
[-6, -3, 1, 4],
[-5, -1, -10, 12]
]
print("Matrix = ",mat)
print("Count of Negative Numbers = ",negativeFunc(mat, 3, 4))
Matrix = [[-1, 3, 5, 7], [-6, -3, 1, 4], [-5, -1, -10, 12]]
Count of Negative Numbers = 6
输出
Matrix = [[-1, 3, 5, 7], [-6, -3, 1, 4], [-5, -1, -10, 12]]
Count of Negative Numbers = 6