As @JanKuiken mentioned, your idea is probably clever, but I can't understand what your code does either! Please add it to the question if possible!
You need more spaces in your code!
Prefer +=
and -=
operators as they are more compact than assignments such as x = x + 1
.
for variable in range(0, end)
is not necessary as range
starts the sequence with 0 by default.
Use meaningful variable names
The variable y
is declared unnecessarily.
a = 1
c = 0
z = 0
x = 1
k = 1
- The above part looks pretty bad. Change it to the below code
c = z = 0
a = x = k = 1
for i in lis: # Faster and smaller!
print(*i, sep='\t')
Here's a glimpse of how your final code might look like:
import math
row = int(input("Input number := "))
lis = [[0] * row for j in range(row)]
c = z = 0
a = x = k = 1
for b in range(math.ceil(row / 2)):
if b == k:
row -= 1
x += 1
z += 1
k += 1
for c in range(z, row):
lis[b][c] = a
a += 1
for d in range(x, row):
lis[d][row-1] = a
a += 1
for e in range(row-1, z, -1):
lis[row-1][e-1] = a
a += 1
for f in range(row-2, z, -1):
lis[f][z] = a
a += 1
for i in lis:
print(*i, sep='\t')
Here's how I'd have approached this problem:
n = int(input('Enter the size of the grid: '))
result = [[0] * n for _ in range(n)]
# Ending points
ei, ej = n // 2, (n - 1) // 2
# 0: RIGHT, 1: DOWN, 2: LEFT, 3: UP
orient = 0
def fill(i: int, j: int, di: int, dj: int, val: int) -> tuple:
"""
'i' is the current row index
'j' is the current column index
'di' is the direction of the row (1: UP, -1: DOWN)
'dj' is the direction of the column (1: RIGHT, -1: LEFT)
'val' is the next value in the spiral
"""
while 0 <= i + di < n and 0 <= j + dj < n:
if result[i + di][j + dj] != 0:
break
i += di
j += dj
result[i][j] = val
val += 1
return i, j, val
# 'j' is -1 because the (0, 0) is yet to be filled
i, j = 0, -1
val = 1
while (i, j) != (ei, ej):
if orient == 0: i, j, val = fill(i, j, 0, 1, val)
if orient == 1: i, j, val = fill(i, j, 1, 0, val)
if orient == 2: i, j, val = fill(i, j, 0, -1, val)
if orient == 3: i, j, val = fill(i, j, -1, 0, val)
orient = (orient + 1) % 4
for i in result:
print(*i, sep='\t')