Python范围的成员资格测试的时间复杂度不一致

时间:2019-06-29 20:05:35

标签: python-3.x range membership

根据文档,自3.2版本以来,Python范围的成员资格测试一直是恒定时间。但是,当我尝试测量它(版本3.7.3)时,当我搜索最大或中间整数时,会观察到线性时间,而对整数进行随机化时,则观察到了恒定时间。这甚至有道理吗?plot of the time complexity for range membership test 代码:

import scipy as sp
from matplotlib import pyplot as plt
import timeit
def in_range(maxlength = 1000, numlengths = 100, numSearch = 1000):
    lengths = sp.linspace(1, maxlength, num = numlengths, dtype = int)
    avgtimes = sp.zeros((3, lengths.size))

    for j, length in zip(range(numlengths), lengths):
        container = range(length)
        # test for last integer in range
        myInt = length-1
        avgtimes[0, j] = timeit.timeit('myInt in container',
                number = numSearch, globals = locals()) / numSearch

        # test for middle-ish integer
        myInt = length//2
        avgtimes[1, j] = timeit.timeit('myInt in container',
                number = numSearch, globals = locals()) / numSearch

        # test for random integer within range
        times = sp.zeros(numSearch)
        for i in range(numSearch):
            myInt = sp.random.randint(0, length)
            times[i] = timeit.timeit('myInt in container', number = 1,
                 globals = locals())
        avgtimes[2, j] = times.mean()

    for j in range(3):
        plt.plot(lengths, avgtimes[j])
    plt.legend(['maximum integer', 'middle-ish integer', 'random integer'])
    plt.xlabel('range size')
    plt.ylabel('average membership test time (seconds)')

0 个答案:

没有答案