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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
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.