0

I'm a student working on this homework problem. The code tries to find a solution to any given circular board game, where a list is given as an argument. The values in the list tell the program how far to move clockwise/counterclockwise (last element is always 0).

The program is meant to return True if there is a solution to that particular puzzle and False otherwise. Except in the case of having 0 as the first and only element, my code returns a RecursionError even for short lists. What's wrong with my code?

def solve_puzzle(L): # uses helper for memoization
    visited = set() # visited indices
    return _solve_puzzle(L, visited, 0)

def _solve_puzzle(L, visited, index): # always start at first element
    if L[index] not in visited:
        visited.add(index)
        if L[index] == 0: 
            return True
        else:
            # loop around to the end or start in python
            if L[index] + index >= len(L):
                new_index_add = index + L[index] - len(L)
            else:
                new_index_add = index + L[index]
            
            if index - L[index] < 0:
                new_index_sub = len(L) - L[index] - index
            else:
                new_index_sub = index - L[index]
                
            # need to figure out the indexing - how do we go both backward and forward
            return _solve_puzzle(L, visited, new_index_add) or _solve_puzzle(L, visited, new_index_sub) # True if it's solveable in either direction
        
    return False

1 Answer 1

0

You should probably add visited = visited.copy() at the top of the function. Otherwise, when visited is modified, it gets modified for every call, since sets are mutable.

I can see two other tiny mistakes, but I think you should figure them out on your own. I don't want to give you the whole answer since it's a homework task. Fix them and it should work. Sorry.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.