Решение на Шахматни фенове от Назифе Алиджик

Обратно към всички решения

Към профила на Назифе Алиджик

Резултати

  • 8 точки от тестове
  • 0 бонус точки
  • 8 точки общо
  • 14 успешни тест(а)
  • 3 неуспешни тест(а)

Код

class ChessException(Exception):
def __init__(self, message):
self._message = message
super().__init__(self._message)
class ChessPosition:
def __init__(self, FEN):
self.FEN = FEN
self.whites = []
self.blacks = []
has_exception_pawns = False
self.rows = FEN.split("/")
for i, row in enumerate(self.rows):
index = 0
for figure in row:
if i == 0 or i == 7:
if figure == "p" or figure == "P":
has_exception_pawns = True
if figure.isnumeric():
index += int(figure)
continue
if figure.islower():
self.blacks.append(figure)
elif figure.isupper():
self.whites.append(figure)
index += 1
self.whites = [figure.lower() for figure in self.whites]
occurrence_white_king = self.whites.count("k")
occurrence_black_king = self.blacks.count("k")
if occurrence_black_king != 1 or occurrence_white_king != 1:
raise ChessException("kings")
elif has_exception_pawns:
raise ChessException("pawns")
def __str__(self):
return f'{self.FEN}'
def __len__(self):
figures = {"k", "q", "p", "r", "n", "b"}
size = 0
for char in self.FEN:
if char.lower() in figures:
size += 1
return size
def get_white_score(self):
return ChessScore(self.whites)
def get_black_score(self):
return ChessScore(self.blacks)
def white_is_winning(self):
return ChessScore(self.whites) > ChessScore(self.blacks)
def black_is_winning(self):
return ChessScore(self.blacks) > ChessScore(self.whites)
def is_equal(self):
return ChessScore(self.whites) == ChessScore(self.blacks)
# def __setitem__(self, key, item):
# self.__dict__[key] = item
# def __getitem__(self, key):
# return self.__dict__[key]
class ChessScore:
def __init__(self, figures):
self.figures = figures
def __lt__(self, other):
return sum_score(self.figures) < sum_score(other.figures)
def __le__(self, other):
return sum_score(self.figures) <= sum_score(other.figures)
def __gt__(self, other):
return sum_score(self.figures) > sum_score(other.figures)
def __eq__(self, other):
return sum_score(self.figures) == sum_score(other.figures)
def __ne__(self, other):
return sum_score(self.figures) != sum_score(other.figures)
def __add__(self, other):
return sum_score(self.figures) + sum_score(other.figures)
def __sub__(self, other):
return sum_score(self.figures) - sum_score(other.figures)
def __str__(self):
return "{0}".format(self.figures)
def __int__(self):
return sum_score(self.figures)
def sum_score(figures):
sum = 0
for figure in figures:
figure.lower()
if figure == 'r':
sum += 5
elif figure == 'n' or figure == 'b':
sum += 3
elif figure == 'q':
sum += 9
elif figure == 'k':
sum += 4
elif figure == 'p':
sum += 1
return sum

Лог от изпълнението

.E...E.....F.....
======================================================================
ERROR: test_against_touching_kings (test.TestChessPosition)
Test for kings next to each other.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/storage/deedee/data/rails/pyfmi-2022/releases/20221115154139/lib/language/python/runner.py", line 67, in thread
    raise result
Exception: No exception raised on: k7/K7/8/8/8/8/8/8

======================================================================
ERROR: test_getitem (test.TestChessPosition)
Test getitem functionality.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/storage/deedee/data/rails/pyfmi-2022/releases/20221115154139/lib/language/python/runner.py", line 67, in thread
    raise result
TypeError: 'ChessPosition' object is not subscriptable

======================================================================
FAIL: test_validation_conflict (test.TestChessPosition)
Test for correct Exception on multiple validation fails.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/storage/deedee/data/rails/pyfmi-2022/releases/20221115154139/lib/language/python/runner.py", line 67, in thread
    raise result
AssertionError: 'pawns' != 'kings'
- pawns
+ kings


----------------------------------------------------------------------
Ran 17 tests in 0.172s

FAILED (failures=1, errors=2)

История (2 версии и 4 коментара)

Назифе обнови решението на 28.11.2022 20:05 (преди почти 2 години)

+class ChessException(Exception):
+
+ def __init__(self, message="kings"):

Бих препоръчал в тялото на класа си просто да сложиш pass, тъй като родителя вече си има същия конструктор, но виждам, че си сложила съобщение по подразбиране. Само споменавам - ако го нямаше, минаваш само с един pass, а при извикване на изключението си дефинираш съобщението експлицитно. Така или иначе смятам за по-добра практика да го дефинираш при всяко извикване, за да е по-лесно да се чете кодът, без да ходя да гледам какво е съобщението по подразбиране.

+ self._message = message
+ super().__init__(self._message)
+
+
+class ChessPosition:
+
+ def __init__(self, FEN):
+ self.FEN = FEN
+ self.whites = []
+ self.blacks = []
+
+ self.rows = FEN.split("/")
+ for i, row in enumerate(self.rows):
+ index = 0
+ for figure in row:
+ if i == 0 or i == 7:
+ if figure == "p":
+ raise ChessException("pawns")
+ if figure.isnumeric():
+ index += int(figure)
+ continue
+ if i % 2 == 0:

Хмм, не разбирам как правиш изводи за цвета на фигурите базирано на индекса. Явно не си разбрала условието правилно. Цвета на фигурата се определя от това дали буквата е малка или главна, а не от цвета на полето върху дъската.

+ if index % 2 == 0:
+ self.blacks.append(figure)
+ else:
+ self.whites.append(figure)
+ index += 1
+ else:
+ if index % 2 == 0:
+ self.whites.append(figure)
+ else:
+ self.blacks.append(figure)
+ index += 1
+
+ self.blacks = [figure.lower() for figure in self.blacks]
+ self.whites = [figure.lower() for figure in self.whites]
+ occurrence_white_king = self.whites.count("k")
+ occurrence_black_king = self.blacks.count("k")
+
+ if occurrence_black_king != 1 or occurrence_white_king != 1:
+ raise ChessException()
+
+ def __str__(self):
+ return f'{self.FEN}'
+
+ def __len__(self):
+ figures = {"k", "q", "p", "r", "n", "b"}
+ size = 0
+ for char in self.FEN:
+ if char.lower() in figures:
+ size += 1
+ return size
+
+ def get_white_score(self):
+ return ChessScore(self.whites)
+
+ def get_black_score(self):
+ return ChessScore(self.blacks)
+
+ def white_is_winning(self):
+ return ChessScore(self.whites) > ChessScore(self.blacks)
+
+ def black_is_winning(self):
+ return ChessScore(self.blacks) > ChessScore(self.whites)
+
+ def is_equal(self):
+ return ChessScore(self.whites) == ChessScore(self.blacks)
+
+ # def __setitem__(self, key, item):
+ # self.__dict__[key] = item
+
+ # def __getitem__(self, key):
+ # return self.__dict__[key]
+
+
+class ChessScore:
+
+ def __init__(self, figures):
+ self.figures = figures
+
+ def __lt__(self, other):
+ return sum_score(self.figures) < sum_score(other.figures)
+
+ def __le__(self, other):
+ return sum_score(self.figures) <= sum_score(other.figures)
+
+ def __gt__(self, other):
+ return sum_score(self.figures) > sum_score(other.figures)
+
+ def __eq__(self, other):
+ return sum_score(self.figures) == sum_score(other.figures)
+
+ def __ne__(self, other):
+ return sum_score(self.figures) != sum_score(other.figures)
+
+ def __add__(self, other):
+ return sum_score(self.figures) + sum_score(other.figures)
+
+ def __sub__(self, other):
+ return sum_score(self.figures) - sum_score(other.figures)
+
+ def __str__(self):
+ return "{0}".format(self.figures)
+
+ def __int__(self):
+ return sum_score(self.figures)
+
+
+def sum_score(figures):
+ sum = 0
+ for figure in figures:
+ figure.lower()
+ if figure == 'r':
+ sum += 5
+ elif figure == 'n' or figure == 'b':
+ sum += 3
+ elif figure == 'q':
+ sum += 9
+ elif figure == 'k':
+ sum += 4
+ elif figure == 'p':
+ sum += 1
+ return sum

Назифе обнови решението на 29.11.2022 10:45 (преди почти 2 години)

class ChessException(Exception):
- def __init__(self, message="kings"):
+ def __init__(self, message):
self._message = message
super().__init__(self._message)
class ChessPosition:
def __init__(self, FEN):
self.FEN = FEN
self.whites = []
self.blacks = []
+ has_exception_pawns = False
self.rows = FEN.split("/")
for i, row in enumerate(self.rows):
index = 0
for figure in row:
if i == 0 or i == 7:
- if figure == "p":
- raise ChessException("pawns")
+ if figure == "p" or figure == "P":
+ has_exception_pawns = True
if figure.isnumeric():
index += int(figure)
continue
- if i % 2 == 0:
- if index % 2 == 0:
- self.blacks.append(figure)
- else:
- self.whites.append(figure)
- index += 1
- else:
- if index % 2 == 0:
- self.whites.append(figure)
- else:
- self.blacks.append(figure)
- index += 1
+ if figure.islower():
+ self.blacks.append(figure)
+ elif figure.isupper():
+ self.whites.append(figure)
+ index += 1
- self.blacks = [figure.lower() for figure in self.blacks]
self.whites = [figure.lower() for figure in self.whites]
occurrence_white_king = self.whites.count("k")
occurrence_black_king = self.blacks.count("k")
-
if occurrence_black_king != 1 or occurrence_white_king != 1:
- raise ChessException()
+ raise ChessException("kings")
+ elif has_exception_pawns:
+ raise ChessException("pawns")
def __str__(self):
return f'{self.FEN}'
def __len__(self):
figures = {"k", "q", "p", "r", "n", "b"}
size = 0
for char in self.FEN:
if char.lower() in figures:
size += 1
return size
def get_white_score(self):
return ChessScore(self.whites)
def get_black_score(self):
return ChessScore(self.blacks)
def white_is_winning(self):
return ChessScore(self.whites) > ChessScore(self.blacks)
def black_is_winning(self):
return ChessScore(self.blacks) > ChessScore(self.whites)
def is_equal(self):
return ChessScore(self.whites) == ChessScore(self.blacks)
# def __setitem__(self, key, item):
# self.__dict__[key] = item
# def __getitem__(self, key):
# return self.__dict__[key]
class ChessScore:
def __init__(self, figures):
self.figures = figures
def __lt__(self, other):
return sum_score(self.figures) < sum_score(other.figures)
def __le__(self, other):
return sum_score(self.figures) <= sum_score(other.figures)
def __gt__(self, other):
return sum_score(self.figures) > sum_score(other.figures)
def __eq__(self, other):
return sum_score(self.figures) == sum_score(other.figures)
def __ne__(self, other):
return sum_score(self.figures) != sum_score(other.figures)
def __add__(self, other):
return sum_score(self.figures) + sum_score(other.figures)
def __sub__(self, other):
return sum_score(self.figures) - sum_score(other.figures)
def __str__(self):
return "{0}".format(self.figures)
def __int__(self):
return sum_score(self.figures)
def sum_score(figures):
sum = 0
for figure in figures:
figure.lower()
if figure == 'r':
sum += 5
elif figure == 'n' or figure == 'b':
sum += 3
elif figure == 'q':
sum += 9
elif figure == 'k':
sum += 4
elif figure == 'p':
sum += 1
return sum