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