print out the content of a squared matrix in clockwise direction in python

Here's an example code that prints out the content of a squared matrix in clockwise direction using a loop:

main.py
def clockwise_matrix(matrix):
    # define boundaries
    top = left = 0
    bottom = right = len(matrix) - 1
    
    # keep looping until all elements have been printed
    while left <= right and top <= bottom:
        
        # print top row from left to right
        for i in range(left, right+1):
            print(matrix[top][i], end=" ")
        top += 1 # move to the next row
        
        # print right column from top to bottom
        for i in range(top, bottom+1):
            print(matrix[i][right], end=" ")
        right -= 1 # move to the previous column
        
        # print bottom row from right to left
        if top <= bottom: # check to avoid duplicates
            for i in range(right, left-1, -1):
                print(matrix[bottom][i], end=" ")
            bottom -= 1 # move to the previous row
            
        # print left column from bottom to top
        if left <= right: # check to avoid duplicates
            for i in range(bottom, top-1, -1):
                print(matrix[i][left], end=" ")
            left += 1 # move to the next column
1092 chars
30 lines

To use this function, you can create a squared matrix as a 2D list, like this:

main.py
matrix = [[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]]
63 chars
4 lines

And then call the function like this:

main.py
clockwise_matrix(matrix)
# Output: 1 2 3 6 9 8 7 4 5
53 chars
3 lines

gistlibby LogSnag