微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

打印矩阵边界元素的Python程序

打印矩阵边界元素的Python程序

Boundary Elements of a Matrix

没有被属于同一矩阵的其他元素包围的元素被称为边界元素。利用这个现象,我们可以构建一个程序。让我们考虑一个输入输出的场景,然后构建一个程序。

输入输出场景

考虑一个矩阵(方阵)

  • The Boundary elements are the elements except the middle elements of the matrix.

  • 矩阵的中间元素是5,除了5之外没有其他中间元素。

  • So, the Boundary elements are 9, 8, 7, 6, 4, 3, 2, and 1 as they are lying in the boundary positions of the matrix.

9  8  7
6  5  4
3  2  1

算法

  • Step 1 − Starting from the initial element of the matrix, traverse the elements of the array, which represents a matrix.

  • 第二步 − 我们使用二维数组遍历矩阵的元素,其中一个维度表示行,另一个维度表示列。因此,外部循环表示矩阵的行,内部循环表示矩阵的列。

  • 步骤 3 - 如果元素属于第一行或最后一行或第一列或最后一列,则该元素可以被视为边界元素并可以打印。

  • 第四步 - 如果不是,则该元素必须被视为非边界元素,并应该被跳过。在这种情况下,应该打印一个空格代替非边界元素。

Example

In the following example, we are going to discuss about the process of finding the boundary elements in a matrix.

def functionToPrint(arra, r, c):
   for i in range(r):
      for j in range(c):
         if (i == 0):
            print(arra[i][j])
         elif (i == r-1):
            print(arra[i][j]) 
         elif (j == 0):
            print(arra[i][j])
         elif (j == c-1):
            print(arra[i][j])
         else:
            print(" ")

if __name__ == "__main__":
   arra = [[1, 2, 3, 4], [5, 6, 7, 8],
      [9, 10, 11, 12], [13, 14, 15, 16]]

   print("The boundary elements of the given matrix are: ")
   functionToPrint(arra, 4, 4)

Output

上述程序的输出如下:

The boundary elements of the given matrix are: 
1
2
3
4
5


8
9


12
13
14
15
16

以上就是打印矩阵边界元素的Python程序的详细内容,更多请关注编程之家其它相关文章

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐