【问题标题】: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。

标签: python algorithm index-error linear-search


【解决方案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 确实达到了该值,则意味着循环从未中断并且元素被找到
      猜你喜欢
      • 2021-03-24
      • 2018-09-13
      • 1970-01-01
      • 2022-10-06
      • 1970-01-01
      • 2020-12-18
      • 2017-04-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多