returning value from list vs dictionary

前端 未结 4 646
我在风中等你
我在风中等你 2021-01-19 15:56

I\'m making a chess engine and for my piece square tables i can use lists or dictionaries. As the implementation of the piece square tables made the engine two times slower,

4条回答
  •  醉梦人生
    2021-01-19 16:42

    As you can see in the python wiki on TimeComplexity, list and dict they both have the same complexity in the average case on getting an item of O(1). So there should be not that much of a difference for simple index based look-ups.

    EDIT: I just wrote a little benchmarking code that gets the first element, one from the center and the last. You see that a list has a small advance (although a deviation of 0.01s is not that large when considering that the code runs 1000000 times).

    In summary I would use a list if I were in your situation, as it also fits better to the problem of an index based request.

    >>> from timeit import Timer
    >>> t=Timer("(l[0], l[3], l[7])","l=[50, 30, 30, 30, 20, 30, 50, 40]")
    >>> sorted(t.repeat(5))
    [0.17861513267149576, 0.17863279532627985, 0.17883092423682, 0.17892576501373014, 0.18901037296996037]
    >>> t=Timer("(l[0], l[3], l[7])","l={0: 50, 1: 30, 2: 30, 3: 30, 4: 20, 5: 30, 6: 50, 7: 40}")
    >>> sorted(t.repeat(5))
    [0.18541179903735383, 0.1855488765975224, 0.1855757545505412, 0.18578041096390052, 0.21753940019925722]
    

提交回复
热议问题