Toliak

stepik python 2.6.11

Jul 29th, 2018
368
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.85 KB | None | 0 0
  1. def print_array(array):
  2.     for i in range(0, len(array)):
  3.         tmp = [array[i][j] for j in range(0, len(array[i]))]
  4.         print(*tmp)
  5.  
  6.  
  7. class Filler():
  8.  
  9.     def __init__(self, size):
  10.         self.number = 1
  11.         self.size = size
  12.         self.direction = 1
  13.         self.position = {"x": -1, "y": 0}
  14.  
  15.     def next(self, array):
  16.         if self.number > self.size ** 2:
  17.             return False
  18.  
  19.         new_position = self.next_position()
  20.         while not (0 <= new_position["y"] < self.size and 0 <= new_position["x"] < self.size
  21.                    and array[new_position["y"]][new_position["x"]] is False):
  22.             self.change_direction()
  23.             new_position = self.next_position()
  24.  
  25.         self.position = new_position
  26.         array[new_position["y"]][new_position["x"]] = self.number
  27.         self.number += 1
  28.  
  29.         # print_array(array)
  30.         return True
  31.  
  32.     def change_direction(self):
  33.         self.direction = self.direction + 1 if self.direction < 3 else 0
  34.         return self.direction
  35.  
  36.     def next_position(self):
  37.         if self.direction == 0:
  38.             return {
  39.                 "x": self.position["x"],
  40.                 "y": self.position["y"] - 1,
  41.             }
  42.         elif self.direction == 1:
  43.             return {
  44.                 "x": self.position["x"] + 1,
  45.                 "y": self.position["y"],
  46.             }
  47.         elif self.direction == 2:
  48.             return {
  49.                 "x": self.position["x"],
  50.                 "y": self.position["y"] + 1,
  51.             }
  52.         elif self.direction == 3:
  53.             return {
  54.                 "x": self.position["x"] - 1,
  55.                 "y": self.position["y"],
  56.             }
  57.  
  58.  
  59. size = int(input())
  60. array = [[False for j in range(0, size)] for i in range(0, size)]
  61.  
  62. filler = Filler(size)
  63. while filler.next(array):
  64.     pass
  65.  
  66. print_array(array)
Advertisement
Add Comment
Please, Sign In to add comment