Решение на Шахматни фенове от Ирина Антонова

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

Към профила на Ирина Антонова

Резултати

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

Код

class ChessException(Exception):
pass
from itertools import repeat
from ChessScore import ChessScore
from chess import ChessException
class ChessPosition:
def __init__(self, fen: str):
self.fen = fen
def fen_to_matrix(self):
matrix = []
for line in self.fen.split('/'):
new_line = []
for s in line:
if s.isnumeric():
new_line.extend(repeat(s, int(s)))
else:
new_line.append(s)
matrix.append(new_line)
n = 8
kings = {}
count_white_kings = 0
count_black_kings = 0
for i in range(n):
for j in range(n):
if matrix[i][j] == 'k':
kings.update({'k': [i, j]})
count_black_kings += 1
elif matrix[i][j] == 'K':
kings.update({'K': [i, j]})
count_white_kings += 1
if (i == 0 or i == 7) and matrix[i][j].lower() == 'p':
raise ChessException('pawns')
if count_black_kings != 1 or count_white_kings != 1:
raise ChessException('kings')
k_black = kings.get('k')
k_white = kings.get('K')
if abs(k_black[0] - k_white[0]) <= 1 and abs(k_black[1] - k_white[1]):
raise ChessException(kings)
def get_white_score(self):
white_pieces = []
for char in self.fen[0:len(self.fen)]:
if 'Z' >= char >= 'A':
white_pieces.append(char.lower())
white_score = ChessScore(white_pieces)
return int(white_score)
def get_black_score(self):
black_pieces = []
for char in self.fen[0:len(self.fen)]:
if 'z' >= char >= 'a':
black_pieces.append(char)
black_score = ChessScore(black_pieces)
return int(black_score)
def white_is_winning(self):
black_score = self.get_black_score()
white_score = self.get_white_score()
return white_score > black_score
def black_is_winning(self):
black_score = self.get_black_score()
white_score = self.get_white_score()
return white_score < black_score
def is_equal(self):
black_score = self.get_black_score()
white_score = self.get_white_score()
return white_score == black_score
class ChessScore:
def __init__(self, piece_list: list[str]):
all_pieces = ('r', 'n', 'b', 'k', 'q', 'p')
for piece in piece_list:
if piece not in all_pieces:
raise Exception("Not correct list of pieces.")
self.score = 0
for piece in piece_list:
match piece:
case 'r':
self.score += 5
case 'n':
self.score += 3
case 'b':
self.score += 3
case 'k':
self.score += 4
case 'q':
self.score += 9
case 'p':
self.score += 1
def __int__(self):
return self.score
def __add__(self, other):
return self.score + other.score
def __sub__(self, other):
return self.score - other.score
def __eq__(self, other):
return self.score == other.score
def __ge__(self, other):
return self.score >= other.score
def __le__(self, other):
return self.score <= other.score
def __lt__(self, other):
return self.score < other.score
def __gt__(self, other):
return self.score > other.score
def __ne__(self, other):
return self.score != other.score

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

No module named 'ChessScore'
  File "/storage/deedee/data/rails/pyfmi-2022/releases/20221115154139/lib/language/python/runner.py", line 114, in main
    loaded_test = importlib.import_module('test', test_module)
  File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/tmp/d20221129-4144380-1vjzygr/test.py", line 3, in <module>
    from solution import *
  File "/tmp/d20221129-4144380-1vjzygr/solution.py", line 6, in <module>
    from ChessScore import ChessScore

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

Ирина обнови решението на 29.11.2022 15:43 (преди почти 2 години)

+class ChessException(Exception):
+ pass
+
+from itertools import repeat
+
+from ChessScore import ChessScore
+from chess import ChessException
+
+
+class ChessPosition:
+ def __init__(self, fen: str):
+ self.fen = fen
+
+ def fen_to_matrix(self):
+ matrix = []
+ for line in self.fen.split('/'):
+ new_line = []
+ for s in line:
+ if s.isnumeric():
+ new_line.extend(repeat(s, int(s)))
+ else:
+ new_line.append(s)
+ matrix.append(new_line)
+ n = 8
+ kings = {}
+ count_white_kings = 0
+ count_black_kings = 0
+ for i in range(n):
+ for j in range(n):
+ if matrix[i][j] == 'k':
+ kings.update({'k': [i, j]})
+ count_black_kings += 1
+ elif matrix[i][j] == 'K':
+ kings.update({'K': [i, j]})
+ count_white_kings += 1
+ if (i == 0 or i == 7) and matrix[i][j].lower() == 'p':
+ raise ChessException('pawns')
+ if count_black_kings != 1 or count_white_kings != 1:
+ raise ChessException('kings')
+ k_black = kings.get('k')
+ k_white = kings.get('K')
+ if abs(k_black[0] - k_white[0]) <= 1 and abs(k_black[1] - k_white[1]):
+ raise ChessException(kings)
+
+ def get_white_score(self):
+ white_pieces = []
+ for char in self.fen[0:len(self.fen)]:
+ if 'Z' >= char >= 'A':
+ white_pieces.append(char.lower())
+ white_score = ChessScore(white_pieces)
+ return int(white_score)
+
+ def get_black_score(self):
+ black_pieces = []
+ for char in self.fen[0:len(self.fen)]:
+ if 'z' >= char >= 'a':
+ black_pieces.append(char)
+ black_score = ChessScore(black_pieces)
+ return int(black_score)
+
+ def white_is_winning(self):
+ black_score = self.get_black_score()
+ white_score = self.get_white_score()
+ return white_score > black_score
+
+ def black_is_winning(self):
+ black_score = self.get_black_score()
+ white_score = self.get_white_score()
+ return white_score < black_score
+
+ def is_equal(self):
+ black_score = self.get_black_score()
+ white_score = self.get_white_score()
+ return white_score == black_score
+
+
+class ChessScore:
+ def __init__(self, piece_list: list[str]):
+ all_pieces = ('r', 'n', 'b', 'k', 'q', 'p')
+ for piece in piece_list:
+ if piece not in all_pieces:
+ raise Exception("Not correct list of pieces.")
+
+ self.score = 0
+ for piece in piece_list:
+ match piece:
+ case 'r':
+ self.score += 5
+ case 'n':
+ self.score += 3
+ case 'b':
+ self.score += 3
+ case 'k':
+ self.score += 4
+ case 'q':
+ self.score += 9
+ case 'p':
+ self.score += 1
+
+ def __int__(self):
+ return self.score
+
+ def __add__(self, other):
+ return self.score + other.score
+
+ def __sub__(self, other):
+ return self.score - other.score
+
+ def __eq__(self, other):
+ return self.score == other.score
+
+ def __ge__(self, other):
+ return self.score >= other.score
+
+ def __le__(self, other):
+ return self.score <= other.score
+
+ def __lt__(self, other):
+ return self.score < other.score
+
+ def __gt__(self, other):
+ return self.score > other.score
+
+ def __ne__(self, other):
+ return self.score != other.score

Махайки импортите, кодът ти получава 8 минаващи и 9 фейващи теста.
Единственото, което мога да дам, е една точка. Утешаваща.
Не е прецедент някой да предава неработещ код заради подобни дребни пропуски и никога не съм си позволявал да давам повече от една. А в повечето случаи дори не давам, така че се надявам да го оценяваш.

Ние се стараем да подготвим sanity тестове, които да използвате, а реално това е грешка, която можеш да хванеш и без тест, а само с рънване на кода си през python. Моля, постарай се и ти да тестваш това, което събмитваш.

Знам, че повечето колеги имат доста домашни и разбирам, че е трудно да се намери време, но ние никога не сме давали срок по-малко от седмица, а винаги масово решенията влизат в последните 24 часа. В твоят случай - 3 часа преди крайния срок.

Целта на по-ранното предаване на домашното, е да получиш своевременна обратна връзка, която да можеш да адресираш и да постигнеш добър резултат. Както виждаш, в рамките на около час си получила обратна връзка, че имаш проблем. Просто трябваше да го адресираш навреме.