I have a question about the Python snail arrangement

Asked 2 years ago, Updated 2 years ago, 68 views

n=4
m=3
k = {}
a=1
b=0
c=0

while c< m*n:
    for i in range(abs(m)):
        b=b+1
        c=c+1
        k[(a,b)] = c
        if c==m*n:
            break

    for i in range(abs(n-1)):
        a=a+1
        c=c+1
        k[(a,b)] = c
        if c==m*n:
            break

    for i in range(abs(m-1)):
        b=b-1
        c=c+1
        k[(a,b)] = c
        if c==m*n:
            break

    for i in range(abs(n-2)):
        a= a-1
        c=c+1
        k[(a,b)] = c
        if c==m*n:
            break

print(k)

If you print this out,

{(1, 1): 1, (1, 2): 2, (1, 3): 3, (2, 3): 12, (3, 3): 13, (4, 3): 14, (4, 2): 7, (4, 1): 18, (3, 1): 19, (2, 1): 10, (2, 2): 11, (5, 3): 15, (5, 2): 16, (5, 1): 17}

It comes out like this, but it comes out as (2,3): 12
(2,3): Isn't 4 correct?
Why did you come out like this?

while-loop python

2022-09-21 10:53

1 Answers

I think it's snail-arrangement homework.

It's not the answer, but I just created a function that allows you to take a picture of the state. While checking with this function, modify the original code to make the correct answer.

def print_k():
    print('-'*15)
    for i in range(1, 6):
        for j in range(1, 6):
            print('%4s'%(k.get((i,j), '')), end='')
        print()


n=4
m=3
k = {}
a=1
b=0
c=0

while c< m*n:
    for i in range(abs(m)):
        b=b+1
        c=c+1
        k[(a,b)] = c
        if c==m*n:
            break
    print_k()

    for i in range(abs(n-1)):
        a=a+1
        c=c+1
        k[(a,b)] = c
        if c==m*n:
            break
    print_k()

    for i in range(abs(m-1)):
        b=b-1
        c=c+1
        k[(a,b)] = c
        if c==m*n:
            break
    print_k()

    for i in range(abs(n-2)):
        a=a-1
        c=c+1
        k[(a,b)] = c
        if c==m*n:
            break
    print_k()

#print(k)
print_k()
---------------
   1   2   3




---------------
   1   2   3
           4        
           5
           6

---------------
   1   2   3
           4
           5
   8   7   6

---------------
   1   2   3
  10       4        
   9       5        
   8   7   6        

---------------
   1   2   3
  10  11  12
   9       5
   8   7   6

---------------
   1   2   3
  10  11  12
   9      13
   8   7  14
          15
---------------
   1   2   3
  10  11  12
   9      13
   8   7  14
  17  16  15
---------------
   1   2   3
  10  11  12
  19      13
  18   7  14
  17  16  15
---------------
   1   2   3
  10  11  12
  19      13
  18   7  14
  17  16  15


2022-09-21 10:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.