Sep-25-2019, 02:37 PM
This is basically a word search solver. I tried to solve the words that must be searched, (list_2), in the matrix board where each character from each word must be sought from.
that is my code and the error I get comes from the if else statements where the col_n has no values( i enumerated the list of that contains the list of board to have columns and rows). I am not sure on how to fix this. Please help.
def search_word(words, board): sol =() solution = "" dir_x = { 1 : "right", -1 : "left"} dir_y ={1: "down", -1: "up"} for row_n, row in enumerate(board): for col_n, letter in enumerate(row): for word in words: for i in range(len(word)): if word[0]==letter: if word[0+i] == (col_n + i).values: solution = (col_n, row_n) return sol +solution, "%s" %(dir_x.value(1))#horizontal right elif word[0+i] == (col_n-i).values: solution = (col_n, row_n) return sol+solution, "%s" %(dir_x.value(-1)) #horizontal left elif word[0+i] == (row_n+i).values.values: solution = (col_n, row) return sol+solution, "%s" %(dir_y.value(1)) #vertical down elif word[0+i] == (row_n-i).values.values: solution = (col_n, row) return sol+solution, "%s" %(dir_y.value(-1)) #vertical up elif word[0+i] == ((row_n+i).values+i).values: solution = (col_n, row) return sol+solution, "%s- %s" %(dir_x.value(1),dir_y.value(1)) #down-right elif word[0+i] == ((row_n-i).values+ i).values: solution = (col_n, row) return sol+solution, "%s- %s" %(dir_x.value(1),dir_y.value(-1)) # up-right elif word[0+i] == ((row_n+i).values -i).values: solution = (col_n, row) return sol+solution, "%s- %s" %(dir_x.value(-1),dir_y.value(1)) # down- left elif word[0+i] == ((row_n -i ).values -i).values: solution = (col_n, row) return sol+solution, "%s- %s" %(dir_x.value(-1),dir_y.value(-1)) # up-left else: print ("Out of bounds") list_1= ["rar", "war", "raw", "rar", "dew", "rod" , "red" ] list_2 =["rar", "aoe", "wed"] answer = search_word(list_2, list_1) print (answer)
that is my code and the error I get comes from the if else statements where the col_n has no values( i enumerated the list of that contains the list of board to have columns and rows). I am not sure on how to fix this. Please help.