Created
March 8, 2019 10:35
-
-
Save adw0rd/f71bdecc808b033d8e92b57a8968beca to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[[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]] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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