is_in_board(n : int, pos : Tuple[int, int]) -> bool Returns True if the pos position is valid for a plate of size n × n; returns False otherwise. The position pos is a pair of indices (i, j). For example, on a 7 × 7 board, position (0.5) is valid but (1.7) is not.
def extract_pos(n, str_pos):
letters = [chr(x ord('a')) for x in range(n)]
numbers = [str(x) for x in range(1,n 1)]
numbers.reverse()
if len(str_pos) < 2 or str_pos[0] not in letters or str_pos[1] not in numbers:
res = None
else:
res = (numbers.index(str_pos[1:]), letters.index(str_pos[0]))
return res
def is_in_board(n,pos):
letters = [chr(x ord('a')) for x in range(n)]
numbers = [str(x) for x in range(1, n 1)]
numbers.reverse()
pos = ''.join([letters[pos[1]], numbers[pos[0]]])
if extract_pos(n,pos) is not None:
return True
else:
return False
How can I return False when the list (pos) index is out of range ?board
CodePudding user response:
At the first line of the function extract_pos
function you know all that you need:
- The size of the plate:
n x n
- The desired indexes:
str_pos
So I would do something like this at the first line of the extract_pos
function:
if int(str_pos[0]) >= n or int(str_pos[1]) >= n or int(str_pos[0]) < 0 or int(str_pos[1]) < 0 :
return 'Out of index'
Then you have to check that return value in the is_in_board
function:
extract_pos_return_value = extract_pos(n,pos)
if extract_pos_return_value is not None and extract_pos_return_value is not 'Out of index':
return True
else:
return False
Full Code:
def extract_pos(n, str_pos):
if int(str_pos[0]) >= n or int(str_pos[1]) >= n or int(str_pos[0]) < 0 or int(str_pos[1]) < 0 :
return 'Out of index'
letters = [chr(x ord('a')) for x in range(n)]
numbers = [str(x) for x in range(1,n 1)]
numbers.reverse()
if len(str_pos) < 2 or str_pos[0] not in letters or str_pos[1] not in numbers:
res = None
else:
res = (numbers.index(str_pos[1:]), letters.index(str_pos[0]))
return res
def is_in_board(n,pos):
letters = [chr(x ord('a')) for x in range(n)]
numbers = [str(x) for x in range(1, n 1)]
numbers.reverse()
pos = ''.join([letters[pos[1]], numbers[pos[0]]])
extract_pos_return_value = extract_pos(n,pos)
if extract_pos_return_value is not None and extract_pos_return_value is not 'Out of index':
return True
else:
return False
CodePudding user response:
I'll try to show you a simpler solution.
First, you do not need to construct lists for letters and for numbers, it is much easier to check the parameter.
Then in your is_in_board
function you have not handled your pos
parameter correctly.
Pleas check this solution:
def extract_pos(n, str_pos):
if 0<=ord(str_pos[0])-ord('a')<n and 0<=ord(str_pos[1])-ord('0')<n:
return ord(str_pos[0])-ord('a'), int(str_pos[1])
else:
return None
def is_in_board(n,pos):
xpos = extract_pos(n,pos)
if xpos != None:
x, y = xpos
if 0<=x<n and 0<=y<n:
return True
return False