How to print spiral shape in python

Find this attached screenshot and help in printing the solution as mentioned in the screenshot. It is asked in job interveiw

#python #pythondoubts #python-practice #job #placement-readiness-module

1 Like

@aakasha063 Try this code

import math

def form_spiral_matrix(N):
n = math.ceil(math.sqrt(N)) # Calculate the smallest square matrix dimension that can accommodate N elements
matrix = [[0 for _ in range(n)] for _ in range(n)]
top = 0
bottom = n - 1
left = 0
right = n - 1
direction = 0 # 0 = right, 1 = down, 2 = left, 3 = up
num = 1

while num <= N:
    if direction == 0:
        for i in range(left, right + 1):
            matrix[top][i] = num
            num += 1
            if num > N:
                break
        top += 1
    elif direction == 1:
        for i in range(top, bottom + 1):
            matrix[i][right] = num
            num += 1
            if num > N:
                break
        right -= 1
    elif direction == 2:
        for i in range(right, left - 1, -1):
            matrix[bottom][i] = num
            num += 1
            if num > N:
                break
        bottom -= 1
    elif direction == 3:
        for i in range(bottom, top - 1, -1):
            matrix[i][left] = num
            num += 1
            if num > N:
                break
        left += 1
    direction = (direction + 1) % 4

return matrix

Example usage:

N = int(input("Enter the value of N: "))
spiral_matrix = form_spiral_matrix(N)

for row in spiral_matrix:
print(row)

Hi @shivrajrtandale98 this code doesn’t provide the expected output. The code should provide numbers printed in a spiral shape as shown in the screenshot above.

Check if N = 15 then it is printing numbers till 15 in spiral format.

1 Like

@aakasha063 Ok… I will get back to you with more accurate code.

1 Like