如何解决线性搜索算法中的索引错误?

Posted

技术标签:

【中文标题】如何解决线性搜索算法中的索引错误?【英文标题】:how do i solve index error in linear search algorithm? 【发布时间】:2020-10-29 07:35:53 【问题描述】:
n = int(input("Enter size of array"))
num = int(input("Enter numbers"))
for i in range(0, n):
    num = int(input(hello.append(num)))
print(hello)
x = int(input("enter number to check!"))
count = 0
while count <= len(hello):
    if (hello[count]==x):
        print("found")
        break
    elif (hello[count]!=x):
        count = count + 1
    else:
        print("not found")
        break

朋友们好,我是 DSA 初学者,我的线性搜索代码中出现错误。如果我输入列表中存在的元素,代码将执行,但如果我输入不存在的元素,它会给我

"if (hello[count]==x): Index Error: list index out of range"

帮助我了解我的代码如何高效。 TNX

【问题讨论】:

索引从0开始,表示最后一个索引比列表长度小1。 【参考方案1】:

如果您获取一个列表的长度,它会为您提供该列表中元素的总数。但是,如果您希望该列表的元素以索引作为元素的总数,那么它将给出超出范围的错误。

例如:

$ l = [3,5,4,7,6]

$len(l)

5

$l[5]

IndexError: 列表索引超出范围

【讨论】:

【参考方案2】:

如果您只想检查号码 x 是否在列表 hello 中,您应该这样做:

if x in hello:
    print('found')
else:
    print('not found')

【讨论】:

【参考方案3】:

count 的最大值应为len(hello)-1,因为这是该数组的最后一个有效索引。只需将循环修改为:

while count < len(hello):
    if (hello[count]==x):
        print("found")
        break
    else:
        count = count + 1
if count==len(hello):
    print("not found")

【讨论】:

谢谢。您的代码有效。但是您能否详细说明第二个 if 语句。到底发生了什么。 TYSM。 如果找到该元素,则循环将中断,count 的值将小于len(list)。如果count 确实达到了该值,则意味着循环从未中断并且元素被找到

以上是关于如何解决线性搜索算法中的索引错误?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用伪代码开发线性搜索和二分搜索算法。?

JavaScript 中常见的搜索算法

JavaScript 中常见的搜索算法

JavaScript 中常见的搜索算法

JavaScript 中常见的搜索算法

线性搜索期间二维数组中的数组索引越界错误[关闭]