【问题标题】:Linear search the given array to give required element index线性搜索给定数组以给出所需的元素索引
【发布时间】:2018-12-01 22:00:32
【问题描述】:

我已经在 Python3 中为线性搜索编码,但没有得到所需的输出。问题如下:

你得到了一个由整数组成的大小为 N 的数组。此外,您还获得了一个元素 M,您需要找到并

如果存在,则打印该元素 M 在数组中最后一次出现的索引,否则打印 -1。考虑这个数组是 1 索引的。

输入格式:第一行由2个整数N和M组成,分别表示数组的大小和要在数组中搜索的元素。

下一行包含 N 个空格分隔的整数,表示数组的元素。 输出格式 如果存在,则打印一个整数,表示数组中最后一次出现的整数 M 的索引,否则打印 -1。

样本输入
5 1

1 2 3 4 1

样本输出
5

arr_len , num = input("Enter length & no to be search: ").split()
#num = int(input("Enter number to search: "))
list_of_elements = list(map(int, input("Enter array to search: ").split()))
found = False
for i in range(len(list_of_elements)):
 temp = list_of_elements[i]
 if(temp == num):
  print('--IF cond working--')
  found = True
  print("%d found at %dth position"%(num,i+1))
  break

if(found == False):
 print("-1")

在这里查看我的代码 (https://ide.geeksforgeeks.org/FSYpglmfnz)

我不明白为什么 if 条件在 for 循环中不起作用

【问题讨论】:

  • 出于显而易见的原因,if found == False: 之类的内容应表示为 if not found:
  • 您在整数列表中找不到num,因为num 是一个字符串。你需要一个num=int(num)。然后您应该从列表末尾开始搜索以找到最后一次出现。

标签: python arrays python-3.x algorithm linear-search


【解决方案1】:

要找到最后一个位置,您可以搜索 BACKWARDS 并在第一个命中时停止:

arr_len, num = 6, 1                    # Test Data
list_of_elements = [1, 2, 3, 4, 1, 6]  # Test Data

pos = -1  # initial pos (not found)
for i in range(arr_len, 0, -1):        # 6,5,4,3,2,1
    temp = list_of_elements[i-1]       # adjust for 0-based index
    if(temp == num):
        pos = i # Store position where num is found
        break

print(pos)

【讨论】:

  • 这是最好的答案,因为平均而言 N/2 比较就足够了(假设分布均匀),而继续进行 N 比较。
【解决方案2】:

这行得通

def find(digit, array):
   if digit not in array:
      return -1

   return max([i for i, x in enumerate(array) if x == digit]) + 1

最后的 +1 被告知要考虑对数组 1 进行索引。

【讨论】:

    【解决方案3】:
    arr_len , num = input("Enter length & no to be search: ").split()
    list_of_elements = list(map(int, input("Enter array to search: ").split()))
    pos = -1  # initial pos (not found)
    for i in range(0, int(arr_len)):
       temp = list_of_elements[i]
       if(temp == int(num)):
           pos = i + 1 # Store latest position where num is found
    
    print(pos)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-11
      • 1970-01-01
      • 2015-01-03
      • 2014-04-19
      • 1970-01-01
      • 2019-06-23
      • 1970-01-01
      相关资源
      最近更新 更多