I am inserting and popping from a Stack in the following code:
open_stack = util.Stack()
start = []
start.append(problem.getStartState())
open_stack.push(start)
while not open_stack.isEmpty():
curr_path = open_stack.pop()
print(type(curr_path))
if problem.isGoalState(curr_path[-1]):
return curr_path
for succ in problem.getSuccessors(curr_path[-1]):
open_stack.push(curr_path.append(succ[0]))
return False
The print(type(curr_path)) returns:
<class 'list'>
<class 'NoneType'>
The error I get is as follows:
File "/home/ljagodz/uoft/search/search.py", line 101, in depthFirstSearch
if problem.isGoalState(curr_path[-1]):
TypeError: 'NoneType' object is not subscriptable
The Stack class I am using is defined as so:
class Stack:
"A container with a last-in-first-out (LIFO) queuing policy."
def __init__(self):
self.list = []
def push(self, item):
"Push 'item' onto the stack"
self.list.append(item)
def pop(self):
"Pop the most recently pushed item from the stack"
return self.list.pop()
def isEmpty(self):
"Returns true if the stack is empty"
return len(self.list) == 0
I cannot understand why the print is acting this way, and why I am getting this error.. The NoneType
error seems common enough, but I cannot find any explanation analogous to the issue I am experiencing here, as far as I can tell I am not accidentally assigning some list method to a variable as in other Stackoverflow questions raising this issue.
The problem most likely comes from
...
for succ in problem.getSuccessors(curr_path[-1]):
open_stack.push(curr_path.append(succ[0]))
the append method of list
will return None
object, not the reference to the resulting list. i.e.
print(curr_path.append(succ[0]))
will print None
. So you appended None
to your stack. Try:
for succ in problem.getSuccessors(curr_path[-1]):
open_stack.push(curr_path + [succ[0]]) #use listcomp
also see List Comprehensions
p.s. you can also use list as stack
edit: minor error