Question

While putting together a Boggle solver, I ran into some strange behavior I was hoping someone could explain to me. I got the function to return a set of possible words, and all I seemed to be missing was a way to prevent the solver from including words which were created by visiting the same square twice in a play. I tried to create a list of already visited squares within the current play (a list of index numbers within the string representing the board) by iterating over the global variable seen (I know this would not be correct) which is used to memoize previously explored paths. However, simply initializing a variable with those values using:

previous_ind = [j for (pre, j) in seen]

within the recursive function find_bwords, somehow effects the index variable i and causes IndexErrors stemming from the last line in find_bwords.

seen = set() #(prefix, index) pairs

def boggle_words(board, minlength=3):
    "Find all the words on this Boggle board; return as a set of words."
    results = set()
    for i, sq in enumerate(board):
        if is_letter(sq):
            find_bwords(board, sq, i, results, minlength)
    return results

def find_bwords(board, pre, start, results, minlength): #adds to seen and results
    global seen
    #prev_ind = [j for (pre, j) in seen]  <---mystery culprit
    if (pre, start) not in seen:
        seen.add((pre, start))
        if len(pre) >= minlength and pre in WORDS:
            results.add(pre)
        if pre in PREFIXES:
            for i in neighbors(start, int(sqrt(len(board)))):
                #print 'index: ', i
                find_bwords(board, pre+board[i], i, results, minlength)

Here is a portion of the printout of indexes before introducing prev_ind:

index:  0
index:  1
index:  2
index:  6
index:  8
index:  12
index:  13
index:  14
index:  1
index:  2

and here is a portion after:

index:  0
index:  -7
index:  -14
index:  -21
index:  -28
index:  -35
index:  -42

Why is this happening?

To be clear, I am not looking for a solution to this assignment, I have solved it another way, I just want to understand what is happening in this instance.

Was it helpful?

Solution

The problem is on this line you are assigning to pre, overwriting the previous value it had:

prev_ind = [j for (pre, j) in seen]  # <---mystery culprit

Try changing it to this and it should work as you expect:

prev_ind = [j for (pre2, j) in seen] 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top