I'm making a task where I need to fill a list of lists of given dimensions with values in a spiral. My solution includes the following steps: 1) I create the list of values that will be "packed" into the list, 2) the script makes 4 steps in a loop: A step - from left to right, B step - from top to bottom, C step - from right back to left and D step to return to the top. Then, the start position is reset and 4 steps are initiated again. Every step is limited by stop values, they are recalculated once the step is over. The code works, actually. But not for any n and m combinations. For instance, it goes fine for n=3 and m=3 or for n=4 and m=3, but it does not work for n=3, m=4 or n=3 and m=5. And I do not understand the problem.
n, m = 3, 4
nums = [i for i in range(1, n * m + 1)] # values that will be placed in a spiral
ml = [[0] * m for _ in range(n)] # the list for values
j_st_A, i_st_B, j_st_C, i_st_D = m, n, 0, 0 # borders for steps
i, j, ind = 0, 0, 0
c1 = 0
while ind < len(nums):
c1 += 1
while j < j_st_A:
ml[i][j] = nums[ind]
print('cycle', c1, " A", ' i=', i, ' j=', j, ' index=', ind, sep='')
ind += 1
j += 1
else:
j -= 1
i += 1
j_st_A -= 1
while i < i_st_B:
ml[i][j] = nums[ind]
print('cycle', c1, " B", ' i=', i, ' j=', j, ' index=', ind, sep='')
ind += 1
i += 1
else:
i -= 1
j -= 1
i_st_B -= 1
while j >= j_st_C:
ml[i][j] = nums[ind]
print('cycle', c1, " C", ' i=', i, ' j=', j, ' index=', ind, sep='')
ind += 1
j -= 1
else:
j += 1
i -= 1
j_st_C += 1
while i > i_st_D:
ml[i][j] = nums[ind]
print('cycle', c1, " D", ' i=', i, ' j=', j, ' index=', ind, sep='')
ind += 1
i -= 1
else:
i += 1
j += 1
i_st_D += 1
print('stops after cylce', c1, ' j_st_A=', j_st_A, ', i_st_B=', i_st_B, ', j_st_C=', j_st_C, ', i_st_D=', i_st_D, sep='')
for row in range(n):
for column in range(m):
print(str(ml[row][column]).ljust(3), end=' ')
The output
cycle1 A i=0 j=0 index=0
cycle1 A i=0 j=1 index=1
cycle1 A i=0 j=2 index=2
cycle1 A i=0 j=3 index=3
cycle1 B i=1 j=3 index=4
cycle1 B i=2 j=3 index=5
cycle1 C i=2 j=2 index=6
cycle1 C i=2 j=1 index=7
cycle1 C i=2 j=0 index=8
cycle1 D i=1 j=0 index=9
stops after cylce1 j_st_A=3, i_st_B=2, j_st_C=1, i_st_D=1
cycle2 A i=1 j=1 index=10
cycle2 A i=1 j=2 index=11
The error is in line 29 (its ml[i][j]=nums[ind] in C step from right to left).
I have placed print commands to follow the indeces, and they look fine. It looks like the script does not fall from the ranges for i, j or values to fill the lists... I have compared between 3x3 and 3x4 cases... What is the mystery? Could someone, please, explain?