def read_board(s): Given a string containing lines of either player pieces or pe
ID: 3599421 • Letter: D
Question
def read_board(s): Given a string containing lines of either player pieces or periods, pick apart the string and generate the corresponding board. Blank lines must be ignored, but if the non-blank lines don't create a rectangular shape (different lines have different lengths) or if other characters show up (neither periods nor upper-case letters), return None instead of a generated board.
• Assume: s is a string.
• Reminder: only periods and upper-case letters are in valid boards, and valid boards are always rectangular. You must check both of these!
• read_board("... ABA ") [['.', '.', '.'] ,['A', 'B', 'A']] • read_board(".. .. OK ") [['.', '.'], ['.', '.'], ['O', 'K']]
• read_board(".... .. NOO ") None #different-length rows
Explanation / Answer
def read_board(s):
# check if string is empty or None return None
if not s:
return None
# create an empty list which will hold all valid lines (non empty lines) in s
lines = []
# get all lines as a list by splitting lines on new line charatcer
tempLines = s.split(' ')
# for each line b=obtained by splitting keep only non empty lines
for line in tempLines:
# check if line is not None/empty
if line:
# append line to lines if it is non empty
lines.append(line)
# number of column will be entry in one line and all lines should have same length
col = len(lines[0])
row = 0
# for each lines
for i in range(len(lines)):
# check if length of line is different from other line, if yes return None
if len(lines[i]) != col:
return None
# if line is just white space don't consider it
if lines[i] == ' ':
continue
row += 1
# for each char in line
for c in lines[i]:
# check if char is in upper case letter, else its an invalid data
if not (c == '.' or c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
return None
# create an empty board as we now know exact number of rows and column
# create a new board
board = []
# add given number of rows
for i in range(row):
# initialise each row with empty
> board.append(one_row)
return board
# fill row and column from lines
for i in range(row):
for j in range(col):
board[i][j] = lines[i][j]
return board
# copy pastable code link: https://paste.ee/p/S3It7
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.