我已经在python3中进行了线性搜索编码,但没有得到所需的输出。问题如下:
你已经得到一个由整数组成的n大小数组。此外,你还得到了一个你需要找到的元素m
如果元素存在于数组中,则在数组中打印该元素的最后一个出现的索引,否则打印1。将此数组视为1索引。
输入格式:第一行由2个整数N和M组成,分别表示数组的大小和要在数组中搜索的元素
下一行包含n个空格分隔的整数,表示数组的元素。
输出格式打印一个整数,表示数组中最后一个整数M的索引,如果存在,否则打印1。
样本输入
51个
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
我不明白为什么在循环中条件不起作用

最佳答案

要找到最后一个位置,可以向后搜索并在第一次击中时停止:

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)

关于python - 线性搜索给定数组以给出所需的元素索引,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50987691/

10-08 22:28
查看更多