python列表搜索和连接性能

时间:2015-01-11 02:39:19

标签: python performance coding-style

我是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:

  1. 使用“in”关键字在Python中搜索O(n)操作列表?如果是这样,最好的方法是什么?
  2. 添加到列表O(1)的头部,就像添加到链表的头部,还是O(n),就像添加到数组的头部一样?如果它是O(n),那么最好的方法是什么?
  3. 请随时指出任何“糟糕”的编码习惯,如果有的话

1 个答案:

答案 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)