Python Program for Program to Print Matrix in Z form
Given a square matrix of order n*n, we need to print elements of the matrix in Z form
Examples:
Input : mat[][] = {1, 2, 3,
4, 5, 6,
7, 8, 9}
Output : 1 2 3 5 7 8 9
Input : mat[][] = {5, 19, 8, 7,
4, 1, 14, 8,
2, 20, 1, 9,
1, 2, 55, 4}
Output: 5 19 8 7 14 20 1 2 55 4
Python3
arr = [[ 4 , 5 , 6 , 8 ],
[ 1 , 2 , 3 , 1 ],
[ 7 , 8 , 9 , 4 ],
[ 1 , 8 , 7 , 5 ]]
n = len (arr[ 0 ])
i = 0
for j in range ( 0 , n - 1 ):
print (arr[i][j], end = " " )
k = 1
for i in range ( 0 , n):
for j in range (n, 0 , - 1 ):
if (j = = n - k):
print (arr[i][j], end = " " )
break
k + = 1
i = n - 1
for j in range ( 0 , n):
print (arr[i][j], end = " " )
|
Output
4 5 6 8 3 8 1 8 7 5
Time complexity: O(n2) for a given square matrix of order n*n
Auxiliary Space: O(1)
Please refer complete article on Program to Print Matrix in Z form for more details!
Using numpy
numpy has several efficient ways to extract rows and diagonals, as illustrated below as follows:
Python3
import numpy as np
def printZform(matrix):
matrix = np.array(matrix)
print ( * matrix[ 0 ], * np.diag(np.fliplr(matrix))[ 1 : - 1 ], * matrix[ - 1 ])
arr = [[ 4 , 5 , 6 , 8 ],
[ 1 , 2 , 3 , 1 ],
[ 7 , 8 , 9 , 4 ],
[ 1 , 8 , 7 , 5 ]]
printZform(arr)
|
Output
4 5 6 8 3 8 1 8 7 5
Last Updated :
29 Nov, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...