使用python写一个在数组中进行顺序查找的程序,要求顺次输入元素,且不输入元素个数,若查找成功则返回元素的下标,否则返回false
时间: 2024-05-14 13:15:02 浏览: 15
以下是一个Python程序,用于在数组中进行顺序查找。该程序要求用户逐个输入元素,直到输入“exit”或“quit”为止。程序会将输入的元素存储在一个列表中,并且在列表中查找用户输入的目标元素。如果找到了目标元素,则返回该元素在列表中的索引;否则返回False。
```python
def sequential_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return False
arr = []
while True:
num = input("请输入一个元素,或输入'exit'或'quit'结束输入:")
if num in ['exit', 'quit']:
break
arr.append(num)
target = input("请输入要查找的元素:")
index = sequential_search(arr, target)
if index is not False:
print("元素", target, "的下标为", index)
else:
print("元素", target, "不存在于列表中。")
```
在上面的程序中,我们首先定义了一个名为`sequential_search`的函数,用于在列表中进行顺序查找。该函数接受两个参数:一个列表和一个目标元素。函数使用for循环遍历列表,如果找到目标元素,则返回该元素在列表中的索引;否则返回False。
接下来,我们创建一个空列表`arr`,并使用一个while循环来逐一请求用户输入元素。当用户输入“exit”或“quit”时,循环停止。我们使用`append()`函数将用户输入的元素添加到`arr`列表中。
接着,我们要求用户输入要查找的元素,并将目标元素和列表传递给`sequential_search`函数。如果函数返回一个数字,我们就打印出目标元素在列表中的索引;否则打印出目标元素不存在于列表中的消息。
示例输出:
```
请输入一个元素,或输入'exit'或'quit'结束输入:3
请输入一个元素,或输入'exit'或'quit'结束输入:5
请输入一个元素,或输入'exit'或'quit'结束输入:2
请输入一个元素,或输入'exit'或'quit'结束输入:4
请输入一个元素,或输入'exit'或'quit'结束输入:exit
请输入要查找的元素:2
元素 2 的下标为 2
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)