Python Program for Program to Print Matrix in Z form

Python Program for Program to Print Matrix in Z form

Printing a matrix in Z-form involves printing the top row, then the diagonal elements from top right to bottom left, and finally, printing the bottom row.

Given a matrix, here's how you can print it in Z-form:

Python Tutorial: Printing Matrix in Z-form

def printZForm(matrix):
    '''
    Function to print the matrix in Z-form.
    '''
    if not matrix:
        return []

    # Get the rows and columns of the matrix
    rows = len(matrix)
    columns = len(matrix[0])

    # Print the top row
    for j in range(columns):
        print(matrix[0][j], end=" ")

    # Print the diagonal elements
    # Start from the top right (1, columns-1) and move downwards and leftwards
    for i in range(1, rows):
        print(matrix[i][columns-i-1], end=" ")

    # Print the bottom row if there are more than 2 rows
    if rows > 2:
        for j in range(columns):
            print(matrix[rows-1][j], end=" ")

# Main function
def main():
    matrix = [
        [1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 10, 11, 12],
        [13, 14, 15, 16]
    ]

    print("Matrix in Z form:")
    printZForm(matrix)

if __name__ == "__main__":
    main()

When you run the above program, it will print the given matrix in Z-form.

Explanation:

  • First, the top row is printed.
  • Then, we traverse the matrix diagonally from the top right to bottom left.
  • Lastly, if the matrix has more than 2 rows, we print the bottom row.

This approach should work for matrices of varying sizes, although the visual effect will be best seen in matrices that have a size of at least 3x3.


More Tags

vertical-scrolling custom-button delete-directory varbinary data-uri magento2 compass-geolocation google-places-api jenkins-blueocean sql-injection

More Programming Guides

Other Guides

More Programming Examples