Maison >développement back-end >Tutoriel Python >Programme Python pour imprimer une matrice en forme de serpent
Dans cet article, nous allons apprendre un programme Python pour imprimer une matrice en motif serpent.
Supposons que nous ayons pris la matrice n x n. Nous allons maintenant imprimer la matrice d'entrée selon un motif de serpent en utilisant les méthodes mentionnées ci-dessous.
Voici les différentes méthodes utilisées pour accomplir cette tâche −
Utiliser des boucles for imbriquées
Inverser des lignes alternatives à l'aide du découpage
Nous allons parcourir toutes les lignes de la matrice. Pour chaque ligne, nous vérifierons si elle est paire ou impaire. Si les lignes sont paires, la matrice est imprimée de gauche à droite, sinon la matrice est imprimée de droite à gauche.
Vous trouverez ci-dessous les algorithmes/étapes pour effectuer la tâche requise. −
Créez une variable pour stocker le nombre de lignes d'une matrice.
Créez une autre variable pour stocker le nombre de colonnes d'une matrice.
Créez une fonction printSnakePattern() qui imprime la matrice sous forme de serpent en acceptant la matrice d'entrée comme argument.
Utilisez le mot-clé global pour rendre les variables de lignes et de colonnes globales.
Utilisez une boucle for pour parcourir les lignes de la matrice.
Utilisez l'instruction if conditionnel pour vérifier si le numéro de ligne actuel est un nombre pair.
Utilisez une autre boucle for imbriquée pour parcourir toutes les colonnes de la ligne actuelle si la condition est vraie.
Imprimez la ligne de la matrice de gauche à droite si la ligne actuelle est pair.
Sinon, si la ligne actuelle est impaire, imprimez les lignes de la matrice de droite à gauche.
Créez une variable pour stocker la matrice d'entrée et imprimez la matrice donnée.
Appelez la fonction printSnakePattern() définie ci-dessus en prenant la matrice d'entrée comme paramètre.
Le programme suivant imprime la matrice d'entrée selon un motif de serpent en utilisant des boucles for imbriquées :
# 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)
Lors de l'exécution, le programme ci-dessus générera le résultat suivant −
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
slicing est une pratique fréquente et celle que les programmeurs utilisent le plus pour résoudre les problèmes efficacement. Considérez une liste Python. Vous devez découper une liste pour accéder à une gamme d'éléments de liste. L'utilisation du colon(:),. un simple opérateur de découpage est une méthode pour y parvenir.
[start:stop:step]
start − Index par où commencer
fin − index de fin
Step − Le nombre de sauts entre i, c'est-à-dire la taille du pas
Le programme suivant imprime la matrice d'entrée selon un motif de serpent en utilisant le découpage.
# 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)
Lors de l'exécution, le programme ci-dessus générera le résultat suivant −
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
Dans cet article, nous avons appris à imprimer la matrice donnée sous forme de serpent en utilisant deux méthodes différentes. Nous avons également appris à utiliser le mot-clé global pour rendre les variables globales. Nous avons également appris à inverser n'importe quel itérable, y compris une liste, un tuple, une chaîne. , etc. via le découpage inversé.
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!