Python 检查矩阵是否是下三角形状
在这篇文章中,我们将学习一个使用Python来检查矩阵是否是下三角形状的程序。
假设我们已经输入了一个矩阵。现在我们将使用以下方法来检查输入矩阵是否是下三角形状。
使用的方法,以下是完成此任务的各种方法:
- 使用嵌套的for循环
什么是下三角矩阵
如果主对角线上方的所有条目都为零,则一个方阵被称为下三角矩阵。
示例
1 0 0 0
2 3 0 0
1 3 7 0
0 4 8 4
方法1:使用嵌套循环
步骤
下面是执行所需任务的算法/步骤:
- 创建一个名为printGivenMatrix()的函数,用于打印给定的矩阵。
-
在printGivenMatrix()函数内部使用for循环遍历给定矩阵的行。
-
使用另一个嵌套的for循环遍历当前行的列。
-
打印当前行和列对应的矩阵元素。
-
创建一个名为checkLowerTriangular()的函数,通过接受输入矩阵作为参数来检查输入矩阵是否为下三角形矩阵。
-
使用for循环遍历矩阵的行数,使用len()函数返回对象中的项目数)。
-
使用另一个嵌套的for循环遍历从(行+1)的列到列的末尾。
-
使用if条件语句检查当前元素是否不等于0(因此下三角形条件失败)。
-
如果条件为真,则使用return语句返回False。
-
如果所有嵌套循环执行完毕都没有返回任何内容,则给定的矩阵为下三角形矩阵,因此返回True。
-
创建一个变量来存储输入矩阵。
-
通过将其作为参数传递给printGivenMatrix()函数来打印给定的矩阵。
-
使用if条件语句通过将输入矩阵作为参数传递给checkLowerTriangular()函数来检查上述定义的函数是否返回true。
-
如果条件为真,则打印输入矩阵作为下三角形矩阵。
-
否则打印输入矩阵不是下三角形矩阵。
示例
以下程序使用嵌套For循环返回给定矩阵是否为下三角形矩阵。
# creating a function to print the given matrix
def printGivenMatrix(inputMatrix):
# Traversing in the rows of the input matrix
for p in range(len(inputMatrix)):
# Traversing in the columns corresponding to the current row
# of the input matrix
for q in range(len(inputMatrix)):
# printing the element at the current row and column
print(inputMatrix[p][q], end=" ")
# Printing a new line to separate the rows
print()
# createing a function to check whether the matrix
# is lower triangular by accepting the input matrix as an argument
def checkLowerTriangular(inputMatrix):
# traversing through the rows of a matrix
for p in range(0, len(inputMatrix)):
# Traversing from row +1 column to last column
for q in range(p + 1, len(inputMatrix)):
# checking whether the current element is not equal to 0
if(inputMatrix[p][q] != 0):
# If the element is not zero then it cannot be considered as lower triangular
# Hence returning false if the condition is true
return False
# If the above nested loops get executed without returning False
# Hence the matrix is lower triangular so return True
return True
# input matrix
inputMatrix = [[1, 0, 0, 0],
[2, 3, 0, 0],
[1, 3, 7, 0],
[0, 4, 8, 4]]
# Printing the given input Matrix by passing the
# given matrix as an argument to printGivenMatrix() function
printGivenMatrix(inputMatrix)
# checking whether the checkLowerTriangular() returns true
if checkLowerTriangular(inputMatrix):
# If the function returns True then the matrix is lower triangular
print("Yes, the input matrix is lower triangular!!!")
else:
# else printing NOT lower triangular matrix
print("No, the input matrix is Not lower triangular!!!")
输出
执行以上程序后,将生成以下输出:
1 0 0 0
2 3 0 0
1 3 7 0
0 4 8 4
Yes, the input matrix is lower triangular!!!
时间复杂度 - O(n^2)。其中 n 表示指定矩阵中的行数和列数。
辅助空间 - O(1)。不需要额外的空间,因此是一个常数。
结论
本文介绍了下三角矩阵的概念和示例,并在最后给出了判断给定矩阵是否为下三角矩阵的代码和说明。