From 708410c89342ae715feefdb60614da28f69a4e57 Mon Sep 17 00:00:00 2001 From: Lubos Kolouch Date: Sun, 13 Sep 2020 12:09:55 +0200 Subject: Refactor the solution 2 --- challenge-077/lubos-kolouch/python/ch-2.py | 39 ++++++++++++++++-------------- 1 file changed, 21 insertions(+), 18 deletions(-) (limited to 'challenge-077/lubos-kolouch/python/ch-2.py') diff --git a/challenge-077/lubos-kolouch/python/ch-2.py b/challenge-077/lubos-kolouch/python/ch-2.py index f77995658d..0e7ffc9c7a 100644 --- a/challenge-077/lubos-kolouch/python/ch-2.py +++ b/challenge-077/lubos-kolouch/python/ch-2.py @@ -12,31 +12,34 @@ class LoneX: self.matrix = matrix self.solution_count = 0 - def count_lone(self): - """ count the occurences of lone X """ + def check_position(self, pos_x: int, pos_y: int): + """ check if the position is lone """ - for line_nr, line in enumerate(self.matrix): - for col_nr, char in enumerate(line): - if char == "O": + for d_x in [-1, 0, 1]: + for d_y in [-1, 0, 1]: + if d_x == d_y == 0: continue - is_lone = True - for d_x in [-1, 0, 1]: - for d_y in [-1, 0, 1]: - if d_x == d_y == 0: - continue + if pos_x + d_x < 0 or pos_x + d_x >= len(self.matrix): + continue + + if pos_y + d_y < 0 or pos_y + d_y >= len(self.matrix): + continue - if line_nr + d_x < 0 or line_nr + d_x >= len(self.matrix): - continue + if self.matrix[pos_x + d_x][pos_y + d_y] == 'X': + return False - if col_nr + d_y < 0 or col_nr + d_y >= len(self.matrix): - continue + return True - if self.matrix[line_nr + d_x][col_nr + d_y] == 'X': - is_lone = False - break + def count_lone(self): + """ count the occurences of lone X """ + + for pos_x, line in enumerate(self.matrix): + for pos_y, char in enumerate(line): + if char == "O": + continue - if is_lone: + if self.check_position(pos_x, pos_y): self.solution_count += 1 def get_count(self): -- cgit