【问题标题】:Binary search python二分查找python
【发布时间】:2021-07-29 18:47:37
【问题描述】:

我正在努力争取时间 二进制搜索的不同大小。我只用这个程序得到 2097152。我是 python 新手。我知道缩进在 python 中是至关重要的。有缩进的东西吗?谢谢

import time
def bsearch(a,first,last,key):
    if first>last:
        #print "not found"
            return
    mid=(first+last)//2
    if key==a[mid]:
        #print "found"
            return
    elif key>a[mid]:
        bsearch(a,mid+1,last,key)
    else:
        bsearch(a,first,mid-1,key)

a=[1]*2097152
sizes=[128,512,2048,8192,32768,131072,524288,2097152]
for i in range(0,8):
    for j in range(0,sizes[i]):
        a[j]=j
start=time.time()
for k in range(0,20000):
    bsearch(a,0,j-1,j)
stop=time.time()
print ("time for size "+str(j)+" is: "+str((stop-start)*1000))

【问题讨论】:

  • 2097152 能得到什么?您的二进制搜索是否有效?您可以尝试使用timeit.timeit,而不是手动尝试计算时差。
  • 由于您的 for 循环 j 的顺序和嵌套在您的测试中始终为 2097152,您希望发生什么?
  • I am expecting something like this - 0.173451093 seconds for 128 1.245498027 seconds for 512 1.152212907 seconds for 2048 1.195236266 seconds for 8192 1.248549547 seconds for 32768 1.286318933 seconds for 131072 1.363635626 seconds for 524288 1.506570667 seconds for 2097152
  • 我得到“尺寸 2097152 的时间是:368.13902854 @Patrick Haugh

标签: python binary-search


【解决方案1】:
from timeit import timeit

for length in [128,512,2048,8192,32768,131072,524288,2097152]:
    l = list(range(length+1))
    command = 'bsearch(l, 0, length, length)'
    print('{:<23} seconds for {}'.format(timeit(command, globals=globals(), number=2000), length))

这是一个使用timeit.timeit 的版本来测量在给定大小的列表上执行bsearch 2000 次所需的时间。在我的机器上,结果是

0.005647999999382591    seconds for 128
0.007602000000588305    seconds for 512
0.009716999999909604    seconds for 2048
0.010829999999259599    seconds for 8192
0.012752000000546104    seconds for 32768
0.0143049999996947      seconds for 131072
0.01644899999973859     seconds for 524288
0.020023000000037428    seconds for 2097152

编辑:

如果您使用的是 globals 将无法在 timeit 中使用。您可以改为 import 来自 __main__

from timeit import timeit

for length in [128,512,2048,8192,32768,131072,524288,2097152]:
    l = list(range(length+1))
    command = 'bsearch(l, 0, length, length)'
    setup = 'from __main__ import bsearch, l, length'
    print('{:<23} seconds for {}'.format(timeit(command, setup=setup, number=2000), length))

【讨论】:

  • 现在我得到了 timeit( ) 有一个意想不到的关键字 'globals'。 @Patrick Haugh
  • 看起来是在 python 3.5 中添加的。请参阅我对适用于旧版本 python 的 sn-p 的编辑。
猜你喜欢
  • 2014-04-10
  • 1970-01-01
  • 2021-03-22
  • 2015-12-02
  • 1970-01-01
  • 2015-12-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多