This is a problem from CodeSignal which can be founded over here
Here is an image on what we have to do:
Code
def map(cell):
new_cell1 = ''
for i in cell:
if i == 'a':
new_cell1 += '1'
if i == 'b':
new_cell1 += '2'
if i == 'c':
new_cell1 += '3'
if i == 'd':
new_cell1 += '4'
if i == 'e':
new_cell1 += '5'
if i == 'f':
new_cell1 += '6'
if i == 'g':
new_cell1 += '7'
if i == 'h':
new_cell1 += '8'
new_cell1 += cell[-1]
return new_cell1
def chessKnight(cell):
cell = map(cell)
num_of_moves = 0
if (int(cell[0])+1 <= 8 and int(cell[0])+1 > 0) and (int(cell[1])+2 <= 8 and int(cell[1])+2 > 0):
num_of_moves += 1
if (int(cell[0])-1 <= 8 and int(cell[0])-1 > 0) and (int(cell[1])+2 <= 8 and int(cell[1])+2 > 0):
num_of_moves += 1
if (int(cell[0])+1 <= 8 and int(cell[0])+1 > 0) and (int(cell[1])-2 <= 8 and int(cell[1])-2 > 0):
num_of_moves += 1
if (int(cell[0])-1 <= 8 and int(cell[0])-1 > 0) and (int(cell[1])-2 <= 8 and int(cell[1])-2 > 0):
num_of_moves += 1
if (int(cell[0])+2 <= 8 and int(cell[0])+2 > 0) and (int(cell[1])+1 <= 8 and int(cell[1])+1 > 0):
num_of_moves += 1
if (int(cell[0])-2 <= 8 and int(cell[0])-2 > 0) and (int(cell[1])+1 <= 8 and int(cell[1])+1 > 0):
num_of_moves += 1
if (int(cell[0])+2 <= 8 and int(cell[0])+2 > 0) and (int(cell[1])-1 <= 8 and int(cell[1])-1 > 0):
num_of_moves += 1
if (int(cell[0])-2 <= 8 and int(cell[0])-2 > 0) and (int(cell[1])-1 <= 8 and int(cell[1])-1 > 0):
num_of_moves += 1
return num_of_moves
Question
The Code works as expected and returns the right answer, but I have just put a bunch of if
conditions which doesn't look nice to me. Is there any way to implement the problem but without so much if
blocks?