搜尋
首頁後端開發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 iterword to make variables global. We also learned how to reverse yterable to make variables global。 , string, etc. via reverse slicing.

以上是Python程式以蛇形模式列印矩陣的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:tutorialspoint。如有侵權,請聯絡admin@php.cn刪除
Python的科學計算中如何使用陣列?Python的科學計算中如何使用陣列?Apr 25, 2025 am 12:28 AM

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

您如何處理同一系統上的不同Python版本?您如何處理同一系統上的不同Python版本?Apr 25, 2025 am 12:24 AM

你可以通過使用pyenv、venv和Anaconda來管理不同的Python版本。 1)使用pyenv管理多個Python版本:安裝pyenv,設置全局和本地版本。 2)使用venv創建虛擬環境以隔離項目依賴。 3)使用Anaconda管理數據科學項目中的Python版本。 4)保留系統Python用於系統級任務。通過這些工具和策略,你可以有效地管理不同版本的Python,確保項目順利運行。

與標準Python陣列相比,使用Numpy數組的一些優點是什麼?與標準Python陣列相比,使用Numpy數組的一些優點是什麼?Apr 25, 2025 am 12:21 AM

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基於基於duetoc的iMplation,2)2)他們的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函數函數函數函數構成和穩定性構成和穩定性的操作,製造

陣列的同質性質如何影響性能?陣列的同質性質如何影響性能?Apr 25, 2025 am 12:13 AM

數組的同質性對性能的影響是雙重的:1)同質性允許編譯器優化內存訪問,提高性能;2)但限制了類型多樣性,可能導致效率低下。總之,選擇合適的數據結構至關重要。

編寫可執行python腳本的最佳實踐是什麼?編寫可執行python腳本的最佳實踐是什麼?Apr 25, 2025 am 12:11 AM

到CraftCraftExecutablePythcripts,lollow TheSebestPractices:1)Addashebangline(#!/usr/usr/bin/envpython3)tomakethescriptexecutable.2)setpermissionswithchmodwithchmod xyour_script.3)

Numpy數組與使用數組模塊創建的數組有何不同?Numpy數組與使用數組模塊創建的數組有何不同?Apr 24, 2025 pm 03:53 PM

numpyArraysareAreBetterFornumericalialoperations andmulti-demensionaldata,而learthearrayModuleSutableforbasic,內存效率段

Numpy數組的使用與使用Python中的數組模塊陣列相比如何?Numpy數組的使用與使用Python中的數組模塊陣列相比如何?Apr 24, 2025 pm 03:49 PM

numpyArraySareAreBetterForHeAvyNumericalComputing,而lelethearRayModulesiutable-usemoblemory-connerage-inderabledsswithSimpleDatateTypes.1)NumpyArsofferVerverVerverVerverVersAtility andPerformanceForlargedForlargedAtatasetSetsAtsAndAtasEndCompleXoper.2)

CTYPES模塊與Python中的數組有何關係?CTYPES模塊與Python中的數組有何關係?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingingangandmanipulatingc-stylarraysinpython.1)usectypestoInterfacewithClibrariesForperfermance.2)createc-stylec-stylec-stylarraysfornumericalcomputations.3)passarraystocfunctions foreforfunctionsforeffortions.however.however,However,HoweverofiousofmemoryManageManiverage,Pressiveo,Pressivero

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脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器