Skip to content

Instantly share code, notes, and snippets.

@adw0rd
Created March 8, 2019 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adw0rd/f71bdecc808b033d8e92b57a8968beca to your computer and use it in GitHub Desktop.
Save adw0rd/f71bdecc808b033d8e92b57a8968beca to your computer and use it in GitHub Desktop.
[[1, 2, 3, 4, 5],
[16, 17, 18, 19, 6],
[15, 24, 25, 20, 7],
[14, 23, 22, 21, 8],
[13, 12, 11, 10, 9]]
import sys
import pprint
def main(num):
x, y, i, step, direction = 0, 0, 0, int(num), 0
matrix = [list(range(num)) for i in range(num)]
for n in range(num**2):
i += 1 # Увеличиваем счетчик шагов (i - итератор)
matrix[y][x] = n + 1 # Записываем в ячейку значение (инкремент нужен для красоты, ибо range начнет с 0)
# Конечно можно сразу указать range(1, num**2 + 1) - как вариант, но писанины больше в итоге, не красиво
if i == step: # Если итератор достиг шага, то
i = 0 # сбрысываем счетчик шагов
step -= direction % 2 ^ 1 # и уменьшаем шаг (каждые две стороны квадрата уменьшает шаг)
direction = (direction + 1) % 4 # Следующее направление вычисляем по модулю (так как 4 стороны у квадрата)
if direction == 0: # top
x += 1
elif direction == 1: # right
y += 1
elif direction == 2: # bottom
x -= 1
elif direction == 3: # left
y -= 1
pprint.pprint(matrix)
if __name__ == '__main__':
main(int(sys.argv[1]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment