【问题标题】:Finding the complexity of a function查找函数的复杂度
【发布时间】:2015-05-22 19:21:24
【问题描述】:

我正在尝试计算下一个函数max_list11 的时间复杂度,它会递归地找到一个列表的最大值:

def max11(L,left,right):
    if left==right:
        return L[left]
    return max(L[left], max11(L,left+1,right))

def max_list11(L):
    return max11(L,0,len(L)-1)

据我发现,时间复杂度应该是O(n),因为该函数所做的是n 2 个对象列表的最大时间,尽管当我计算运行时间时,我得到运行时间的多项式增长(显然O(n²)),我想知道为什么会这样。

我用这种方式计时:

def elasped(f,L):
    t0 = time.clock()
    s = f(L)
    return(time.clock()-t0)

def avg_elasped(f,L,times = 100):
    measurements = []
    for i in range(times):
        measurements += [elasped(f,L)]
    return sum(measurements)/times

然后我尝试了 1000、2000、...、10000 个长列表。

【问题讨论】:

  • 因为你的时机不好。这是O(n),我有自己的时间来展示它。
  • 无论你说什么,我想你都是对的。我不相信我做错了什么,但是当我计算运行时间时,我在 Excel 中得到了一个完美的抛物线。
  • 你是怎么计时的?
  • 用计时器编辑。

标签: python max time-complexity complexity-theory


【解决方案1】:

递归方法每次调用都会将输入大小减少一个,因此它在理论上是线性的(因为您实际上是在对最大值进行线性搜索)。 Python 列表的实现会扭曲基于计时器的分析。

【讨论】:

    【解决方案2】:

    它是线性的:

    %timeit max_list11(range(10))
    100000 loops, best of 3: 6.93 µs per loop
    
    %timeit max_list11(range(100))
    10000 loops, best of 3: 66.7 µs per loop
    
    %timeit max_list11(range(1000))
    1000 loops, best of 3: 775 µs per loop
    
    %timeit max_list11(range(10000))
    100 loops, best of 3: 9.82 ms per loop
    

    始终使用timeit.default_timer() 作为时间戳。或 IPython,就像我为此输出所做的那样。 time.clock() 根据您的操作系统有不同的含义。来自docs

    在 Unix 上,以浮点数形式返回当前处理器时间,以秒为单位。精度,实际上是“处理器时间”含义的定义,取决于同名 C 函数的精度。

    在 Windows 上,此函数根据 Win32 函数 QueryPerformanceCounter() 以浮点数形式返回自第一次调用此函数以来经过的挂钟秒数。分辨率通常优于 1 微秒。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-18
      • 2018-07-23
      • 1970-01-01
      • 1970-01-01
      • 2021-04-08
      • 2017-04-12
      • 2015-03-03
      相关资源
      最近更新 更多