#python #инспекция_кода
class Knight:
def __init__(self, row, col, color):
self.COLOR = color
if -1 < row < 8 and -1 < col < 8:
self.row, self.col = row, col
else:
print('Находится в неправильном месте')
def can_move(self, r, c):
if -1 < r < 8 and -1 < c < 8:
able_to_move = []
able_to_move.append((self.row - 2, self.col - 1))
able_to_move.append((self.row - 1, self.col - 2))
able_to_move.append((self.row + 1, self.col - 2))
able_to_move.append((self.row + 2, self.col - 1))
able_to_move.append((self.row + 2, self.col + 1))
able_to_move.append((self.row + 1, self.col + 2))
able_to_move.append((self.row - 1, self.col + 2))
able_to_move.append((self.row - 2, self.col + 1))
able_to_move = filter(lambda x: -1 < x[0] < 8 and -1 < x[1] < 8, able_to_move)
return (r, c) in able_to_move
else:
return False
def set_position(self, row1, col1):
if self.can_move(row1, col1):
self.row = row1
self.col = col1
думаю, полезно будет это не только мне.
как вот эту длинную часть:
able_to_move = []
able_to_move.append((self.row - 2, self.col - 1))
able_to_move.append((self.row - 1, self.col - 2))
able_to_move.append((self.row + 1, self.col - 2))
able_to_move.append((self.row + 2, self.col - 1))
able_to_move.append((self.row + 2, self.col + 1))
able_to_move.append((self.row + 1, self.col + 2))
able_to_move.append((self.row - 1, self.col + 2))
able_to_move.append((self.row - 2, self.col + 1))
преобразовать в красивый и лаконичный код? Я пытался найти закономерности и даже
нашел, но к сожелению, сложить это все в нормальную картину не получилось.
(принципиально новые методы решения, с полным перелопатыванием кода и комментариями,
приветствуются)
Ответы
Ответ 1
def can_move(self, r, c): return -1 < r < 8 and -1 < c < 8 and abs((self.row - r) * (self.col - c)) == 2 Upd1: Произведение целых чисел может дать двойку по модулю только в восьми случаях. Другими словами, если расстояние по вертикали 2, а по горизонтали 1 или наоборот - модуль произведения будет равен двум. Upd2: def can_move(self, r, c): if -1 < r < 8 and -1 < c < 8: dx = self.col - c dy = self.row - r return dx in [-2, 2] and dy in [-1, 1] or dx in [-1, 1] and dy in [-2, 2] else: return FalseОтвет 2
from operator import add, sub def can_move(self, r, c): positions = [(f1(self.row, rshift), f2(self.column, cshift)) for f1 in (add, sub) for f2 in (add, sub) for (rshift, cshift) in ((1, 2), (2, 1)) ] able_to_move = [(rn, cn) for (rn, cn) in positions if (0 <= rn <= 7) and (0 <= rn <= 7) ] return (r, c) in able_to_move
Комментариев нет:
Отправить комментарий