Using recursion to find words in a word search

1.9k views Asked by At

I'm having a little fun with python3 by trying to find words in a word search. I know I could easily do this with loops however, I don't know recursion too well and I really want to know how to do it this way.

I began by creating a 2-D list of the rows in the word search and calling that list "square". I created another list of the individual words I am looking for called "word" (for the sake of simplicity, let's pretend there is only one word).

I am going to use recursive functions for each direction a word can go and run the word in each function, returning True if it is found, and False if it is not.

This is the first function:

def down(word, square):
    if (len(word)==0):
      return True
    elif (len(square)==0):
      print(square)
      return False
    else:
      if word[:1]==square[0][:1]:
        return down(word[1:], square[1:])
      elif (word[:1]!=square[0][:1]):
        print(square)
        return down(word, square[1:][1:])
      else:
        return False

This function will try to find the first letter of the word in the 2-D list and then check that same position where the first letter is found in each subsequent line of the square to see if the rest of the word is found.

I cannot get the function to go past the first letter of each 1-D list within the overall 2-D list and any assist would be greatly appreciated.

Thanks!

0

There are 0 answers