Python 线性搜索算法效率的推导

Python 线性搜索算法效率的推导,python,algorithm,Python,Algorithm,对于未排序列表上的简单线性搜索,我的教科书如下所示: 要确定平均情况,请添加在每个可能位置查找目标所需的迭代次数,并将总和除以n。因此,该算法执行(n+n-1+n-2+…+1)/n或(n+1)/2次迭代 他使用的代码示例如下: def sequentialSearch(target, lyst): """Returns the position of the target item if found, or -1 otherwise.""" position = 0 wh

对于未排序列表上的简单线性搜索,我的教科书如下所示:

要确定平均情况,请添加在每个可能位置查找目标所需的迭代次数,并将总和除以n。因此,该算法执行(n+n-1+n-2+…+1)/n或(n+1)/2次迭代

他使用的代码示例如下:

def sequentialSearch(target, lyst):
    """Returns the position of the target item if found, or -1 otherwise."""
    position = 0
    while position < len(lyst):
        if target == lyst[position]:
            return position
        position += 1
    return False
def顺序搜索(目标,lyst):
“”“如果找到,则返回目标项的位置,否则返回-1。”“”
位置=0
当位置

我很难理解他是如何从上面推导(n+1)/2的

当你迭代一个列表以到达可能的目标时,你可能会尝试找到它。所以如果你想找到avg案例。它将是它们的相加,再除以n<代码>(n+n-1+…+2+1)/n
。我们知道
(n+n-1+…+2+1)=n(n+1)/2
。所以我们得到的答案是
n(n+1)/2*n
,这是
(n+1)/2
作为avg的情况

e、 g.用于线性搜索

 lyst = [4,5,2,1,6]
 possibilities of targets = 4 or 5 or 2 or 1 or 6
 target = 4
 attemps reqd = 1 as found in first attempt i.e first location
 lyst = [4,5,2,1,6]
 target = 5
 attemps reqd = 2 as found in second attempt i.e second location
 lyst = [4,5,2,1,6]
 target = 2
 attemps reqd = 3 as found in third attempt i.e third location
 lyst = [4,5,2,1,6]
 target = 1
 attemps reqd = 4 as found in fourth attempt i.e fourth location
 lyst = [4,5,2,1,6]
 target = 6
 attemps reqd = 5 as found in fifth attempt i.e fifth location

 sum of all attempts reqired = 1 + 2 + 3 + 4 + 5 = 15 
 same as n(n+1)/2 = 5(5+1)/2 = 5*3 = 15

 avg case = (1+2+3+4+5)/n = 15/5 = 3
 same as n(n+1)/2*n = 5(6)/2*5 = (n+1)/2 = 6/2 = 3

平均值是指所有元素的总和除以元素数

它只是O(n)而不是n(n+1)/2。n(n+1)/2只是从1到1的所有数字的总和。你想知道为什么算法平均执行
(n+n-1+n-2+…+1)/n
迭代,或者为什么
(n+n-1+n-2+…+1)/n==(n+1)/2
?我认为如果不知道如何对算术序列求和,就无法通过CS101,所以你需要复习你的高中代数或者其他什么。对于第一个问题,搜索的项目可以位于位置1或2或。。。或者n-1或n,求平均值,把它们加起来,除以病例数。@flybonzai。如果你不懂什么,没什么好担心的。如果有毅力,学习速度慢的人最终会变得聪明很多倍。谢谢:)我在自学计算机科学,所以我没有一些程序员已经具备的数学背景。(n+1)/2不是和O(logn)一样吗?不,那是在排序列表上进行的二进制搜索。它是将列表除以二,然后检查它是小还是大,如果不是,则找到目标,否则要检查的列表是左半部分还是右半部分。(n+1)/2是avg案例,与bigO无关