gpt4 book ai didi

python - 线性搜索给定数组以给出所需的元素索引

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:38:17 26 4
gpt4 key购买 nike

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

You have been given an array of size N consisting of integers. In addition you have been given an element M you need to find and

print the index of the last occurrence of this element M in the array if it exists in it, otherwise print -1. Consider this array to be 1 indexed.

Input Format: The first line consists of 2 integers N and M denoting the size of the array and the element to be searched for in the array respectively .

The next line contains N space separated integers denoting the elements of of the array. Output Format Print a single integer denoting the index of the last occurrence of integer M in the array if it exists, otherwise print -1.

SAMPLE INPUT
5 1

1 2 3 4 1

SAMPLE OUTPUT
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 循环中不起作用

最佳答案

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com