我是Python的新手,正在寻找对我写的简单DFS代码的一些批评:
def depthFirstSearch(problem):
return depthFirstSearchRec(problem.getStartState(), problem)
def depthFirstSearchRec(currentState, problem, visited=[]):
if currentState in visited:
return None
else:
visited.append(currentState)
if problem.isGoalState(currentState):
return []
for successor, action, _ in problem.getSuccessors(currentState):
actions = depthFirstSearchRec(successor, problem)
if actions is not None:
return [action] + actions
return None
Qeustions:
答案 0 :(得分:1)
Python list
是一个在内存中紧凑的数组,比如C ++的std::vector
。因此,in
运算符为O(N)
并添加到任何位置,但list
的结尾也是O(N)
。解决方案是使用不同的数据结构 - 有一个很多! - 取决于你想要完成的是什么。
假设您的states
是可以播放的(如果您希望表现良好,则最好!),visited
应为set
- 添加到集合中并使用in
运算符都是O(1)
(因为集合在内部实现为哈希表)。
对于actions
,最简单的想法可能是使用collections.deque
而不是列表 - 双端队列O(1)
用于在任一端追加或删除(尽管列表要快得多,如果所有添加和删除都在右端,也会O(1)
。