微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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入门者,我在线性搜索代码中遇到错误。如果我输入列表中存在的元素,则会执行代码,但是如果我输入不存在的元素,则会给我“如果(hello [count] == x):索引错误:列表索引超出范围”。请帮助我我的代码可以高效。 TNX

解决方法

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

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

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

例如:

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

$ len(l)

5

$ l [5]

IndexError:列表索引超出范围

,

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")

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。