搜索
首页后端开发Python教程Python程序以蛇形模式打印矩阵

Python程序以蛇形模式打印矩阵

在本文中,我们将学习一个Python程序,以蛇形模式打印矩阵。

Assume we have taken the n x n matrix. We will now print the input matrix in a snake pattern using the below-mentioned methods.

Methods Used

The following are the various methods used to accomplish this task −

  • 使用嵌套的for循环

  • Reversing Alternate Rows Using Slicing

直觉 

我们将迭代遍历矩阵的所有行。对于每一行,我们将检查它是偶数还是奇数。如果行是偶数,则从左到右打印矩阵,否则从右到左打印矩阵。

Method 1: Using the nested for loop

算法(步骤)

以下是执行所需任务的算法/步骤。−

  • Create a variable to store the number of rows of a matrix.

  • Create another variable to store the number of columns of a matrix.

  • 创建一个函数printSnakePattern(),通过接受输入矩阵作为参数以蛇形模式打印矩阵。

  • Use the global keyword to make the rows and columns variables global.

  • 使用for循环遍历矩阵的行。

  • 使用if条件语句来检查当前行号是否为偶数。

  • Use another nested for loop to traverse through all the columns of the current row if the condition is true.

  • Print the matrix row from left to right if the current row is even.

  • 否则,如果当前行是奇数,则从右到左打印矩阵行。

  • Create a variable to store the input matrix and print the given matrix.

  • 通过将输入矩阵作为参数调用上述定义的 printSnakePattern() 函数。

Example

以下程序使用嵌套的for循环以蛇形模式打印输入矩阵:

# initializing the number of rows of the matrix
rows = 4
# initializing the number of columns of the matrix
columns = 4
# creating a function for printing the matrix in
# snake pattern accepting the input matrix as an argument.
def printSnakePattern(inputMatrix):
   # making the rows and columns variables global
      global rows, columns
      # traversing through the rows of a matrix
      for m in range(rows):
         # checking whether the current row number is even
         if m % 2 == 0:
            # traversing through all the columns of the current row
               for n in range(columns):
                  # printing from left to right if the current row is even
                  print(inputMatrix[m][n], end=" ")

         # Else, printing from right to left if the current row is even
         else:
            # traversing from the end of the columns
               for n in range(columns - 1, -1, -1):
                  print(inputMatrix[m][n], end=" ")
# input matrix
inputMatrix = [[3, 4, 5, 6],
               [10, 40, 60, 80],
               [1, 9, 7, 8],
               [40, 20, 14, 15]]
print("The Given Matrix is :")
print(inputMatrix)
# calling the above-defined printSnakePattern function
# by passing the input matrix as an argument.
print("Snake Pattern of the given Matrix is:")
printSnakePattern(inputMatrix)

输出

On executing, the above program will generate the following output −

The Given Matrix is :
[[3, 4, 5, 6], [10, 40, 60, 80], [1, 9, 7, 8], [40, 20, 14, 15]]
Snake Pattern of the given Matrix is:
3 4 5 6 80 60 40 10 1 9 7 8 15 14 20 40 

方法2:使用切片反转交替行

slicing is a frequent practice and the one that programmers utilize the most to solve problems effectively. Consider a Python list. You must slice a list to access a range of list elements. The use of the colon(:), a simple slicing operator, is one method for accomplishing this.

Syntax

[start:stop:step]

参数

  • start − 从哪里开始的索引

  • end − ending index

  • 步骤 − 在i之间要跳跃的次数,即步长

Example

以下程序使用切片以蛇形模式打印输入矩阵。

# input matrix
inputMatrix = [[3, 4, 5, 6],
               [10, 40, 60, 80],
               [1, 9, 7, 8],
               [40, 20, 14, 15]]
# initializing the number of rows of a matrix
rows = 4
# initializing the number of columns of a matrix
columns = 4
# creating a function for printing the matrix in
# snake pattern accepting the input matrix as an argument.
def printSnakePattern(inputMatrix):
   # making the rows and columns variables global
      global rows, columns
      # traversing through the rows of a matrix
      for m in range(rows):
         # checking whether the current row number is even
         if m % 2 != 0:
            # Reversing the row using reverse slicing
            inputMatrix[m] = inputMatrix[m][::-1]

      # traversing through the rows of a matrix
      for m in range(rows):
         # traversing through all the columns of the current row
         for n in range(columns):
            # printing the corresponding element
               print(inputMatrix[m][n], end=' ')
# input matrix
inputMatrix = [[3, 4, 5, 6],
               [10, 40, 60, 80],
               [1, 9, 7, 8],
               [40, 20, 14, 15]]
print("The Given Matrix is :")
print(inputMatrix)
# calling the above-defined printSnakePattern function
# by passing the input matrix as an argument.
print("Snake Pattern of the given Matrix is:")
printSnakePattern(inputMatrix)

输出

On execution, the above program will generate the following output −

The Given Matrix is :
[[3, 4, 5, 6], [10, 40, 60, 80], [1, 9, 7, 8], [40, 20, 14, 15]]
The Snake Pattern of the given Matrix is:
3 4 5 6 80 60 40 10 1 9 7 8 15 14 20 40 

Conclusion

In this article, we learned how to print the given matrix in snake form using two different methods. We learned how to use the global keyword to make variables global. We also learned how to reverse any iterable, including a list, tuple, string, etc. via reverse slicing.

以上是Python程序以蛇形模式打印矩阵的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:tutorialspoint。如有侵权,请联系admin@php.cn删除
Python:探索其主要应用程序Python:探索其主要应用程序Apr 10, 2025 am 09:41 AM

Python在web开发、数据科学、机器学习、自动化和脚本编写等领域有广泛应用。1)在web开发中,Django和Flask框架简化了开发过程。2)数据科学和机器学习领域,NumPy、Pandas、Scikit-learn和TensorFlow库提供了强大支持。3)自动化和脚本编写方面,Python适用于自动化测试和系统管理等任务。

您可以在2小时内学到多少python?您可以在2小时内学到多少python?Apr 09, 2025 pm 04:33 PM

两小时内可以学到Python的基础知识。1.学习变量和数据类型,2.掌握控制结构如if语句和循环,3.了解函数的定义和使用。这些将帮助你开始编写简单的Python程序。

如何在10小时内通过项目和问题驱动的方式教计算机小白编程基础?如何在10小时内通过项目和问题驱动的方式教计算机小白编程基础?Apr 02, 2025 am 07:18 AM

如何在10小时内教计算机小白编程基础?如果你只有10个小时来教计算机小白一些编程知识,你会选择教些什么�...

如何在使用 Fiddler Everywhere 进行中间人读取时避免被浏览器检测到?如何在使用 Fiddler Everywhere 进行中间人读取时避免被浏览器检测到?Apr 02, 2025 am 07:15 AM

使用FiddlerEverywhere进行中间人读取时如何避免被检测到当你使用FiddlerEverywhere...

Python 3.6加载Pickle文件报错"__builtin__"模块未找到怎么办?Python 3.6加载Pickle文件报错"__builtin__"模块未找到怎么办?Apr 02, 2025 am 07:12 AM

Python3.6环境下加载Pickle文件报错:ModuleNotFoundError:Nomodulenamed...

如何提高jieba分词在景区评论分析中的准确性?如何提高jieba分词在景区评论分析中的准确性?Apr 02, 2025 am 07:09 AM

如何解决jieba分词在景区评论分析中的问题?当我们在进行景区评论分析时,往往会使用jieba分词工具来处理文�...

如何使用正则表达式匹配到第一个闭合标签就停止?如何使用正则表达式匹配到第一个闭合标签就停止?Apr 02, 2025 am 07:06 AM

如何使用正则表达式匹配到第一个闭合标签就停止?在处理HTML或其他标记语言时,常常需要使用正则表达式来�...

如何绕过Investing.com的反爬虫机制获取新闻数据?如何绕过Investing.com的反爬虫机制获取新闻数据?Apr 02, 2025 am 07:03 AM

攻克Investing.com的反爬虫策略许多人尝试爬取Investing.com(https://cn.investing.com/news/latest-news)的新闻数据时,常常�...

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境