Python程序在数组中搜索元素

python程序在数组中搜索元素

In Python, there are mainly two searching algorithms that are majorly used. Out of those, the first one is Linear Search and the second one is Binary Search.

These two techniques are majorly used in order to search an element from the given array or from the given list also. While searching an element, there are two methodologies that can be followed in any kind of algorithm. One of those is recursive approach and the other is iterative approach. Let us discuss both algorithms in both approaches and solve similar problems.

Linear Search

The Linear Search technique is also known as Sequential search. The meaning of the name “ Sequential search ” is definitely justified by the process followed by this search algorithm. It is a method or technique which is used in order to find the elements within an array or a list in Python.

它被认为是所有其他搜索算法中最简单和最容易的。但是,这个算法的唯一缺点是效率不高。这就是为什么不经常使用线性搜索的主要原因。

立即学习“Python免费学习笔记(深入)”;

算法

Step 1 − It searches for an element in a sequential order just by comparing the desired element with each element present in the given array.

步骤 2 − 如果找到所需的元素,则会将元素的索引或位置显示给用户。

Step 3 − If the element is not present within the array, then the user will be informed that the element is not found. In this way, the algorithm is processed.

In general, Linear search algorithm is comparatively suitable and efficient for small arrays or small lists which has a size less than or equal to 100 as it checks and compares with each element.

如果所需元素位于数组的最后位置,将会消耗更多时间。

线性搜索算法在最佳情况下的时间复杂度为“ O( 1 ) ”。在这种情况下,元素将位于数组的第一个位置,即索引为“ 0 ”。

The Time complexity of Linear Search algorithm in average case is “ O( n ) ”. In this case, the element will be present in the middle position of the array, i.e., with the index “ ( n – 1 ) / 2 ” or “ (( n – 1 ) / 2 )+ 1 ”.

The Time complexity of Linear Search algorithm in worst case is “ O( n ) ”. In this case, the element will be present in the last position of the array, i.e., with the index “ n-1 ”.

Example

在下面的示例中,我们将学习使用线性搜索在数组中查找元素的过程。

def iterative_linear( arr, n, key_element):   for x in range(n):      if(arr[x] == key_element):         return x   return -1arr = [2, 3, 5, 7, 9, 1, 4, 6, 8, 10]max_size = len(arr)key = 8result = iterative_linear(arr, max_size - 1, key)if result != -1:   print ("The element", key," is found at the index " ,(result), "and in the ", (result+1), "position")else:   print ("The element %d is not present in the given array" %(key))

Output

上述程序的输出如下:

The element 8  is found at the index  8 and in the  9 position

Example (Recursive)

在下面的例子中,我们将学习使用递归方法在数组中进行线性搜索的过程。

def recursive_linear( arr, first_index, last_index, key_element):   if last_index < first_index:      return -1   if arr[first_index] == key_element:      return first_index   if arr[last_index] == key_element:      return last_index     return recursive_linear(arr, first_index + 1, last_index - 1, key_element)arr = [2, 3, 5, 7, 9, 1, 4, 6, 8, 10]max_size = len(arr)key = 8result = recursive_linear(arr, 0, max_size - 1, key)if result != -1:   print ("The element", key," is found at the index " ,(result), "and in the ", (result+1), "position")else:   print ("The element %d is not present in the given array" %(key))

Output

上述程序的输出如下:

The element 8  is found at the index  8 and in the  9 position

Binary Search

二分查找算法与线性查找算法相当不同。它遵循完全不同的过程来搜索数组中的元素。它通常只考虑有序数组。

如果数组在某些情况下没有排序,则对数组进行排序,然后开始二分搜索算法的过程。一旦数组被二分搜索算法考虑,它首先被排序,然后算法被应用于数组。

算法

步骤 1 − 对数组进行排序是第一步。

Step 2 − After the array is sorted, the array is considered as two halves. One half is starting from the first element to the middle element of the sorted array and the second half is starting from the element after the middle element to the last element of the sorted array.

Step 3 − The key element (the element that is supposed to be searched is known as key element) is compared with the middle element of the sorted array.

Step 4 − If the key element is less than or equal to the middle element of the sorted array, the second half elements are ignored further as the key element is smaller than the middle element. So, definitely, the element must be present in between the first element and the middle element.

Step 6 − If the key element is greater than the middle element, then the first half of the sorted array is ignored and the elements from the middle element to the last element are considered.

Step 7 − Out of those elements, the key element is again compared with the middle element of the halved array and repeats the same procedure. If the key element is greater than the middle element of the halved array, then the first half is neglected.

第8步 – 如果关键元素小于或等于被分割数组的中间元素,则被分割数组的后半部分将被忽略。通过这种方式,元素将在数组的任意一半中进行搜索。

因此,与线性搜索相比,复杂度减少了一半或更多,因为有一半的元素将在第一步中被移除或不被考虑。二分搜索的最佳情况时间复杂度为“O(1)”。二分搜索的最坏情况时间复杂度为“O(logn)”。这就是二分搜索算法的工作原理。让我们考虑一个例子,并应用二分搜索算法来找出数组中的关键元素。

Example

In this example, we are going to learn about the process of searching an element in an array using Binary search in recursive approach.

def recursive_binary(arr, first, last, key_element):   if first  key_element:      return recursive_binary(arr, first, mid - 1, key_element)   elif arr[mid] < key_element:        return recursive_binary(arr, mid + 1, last, key_element)     else:        return -1 arr = [20, 40, 60, 80, 100] key = 80 max_size = len(arr)result = recursive_binary(arr, 0, max_size - 1, key)  if result != -1:     print("The element", key, "is present at index", (result), "in the position", (result + 1)) else:     print("The element is not present in the array") 

Output

上述程序的输出如下:

The element 80  is found at the index 3 and in the position 4

Example

In this example, we are going to learn about the process of searching an element in an array using Binary search in iterative approach.

def iterative_binary(arr, last, key_element):   first = 0   mid = 0   while first <= last:       mid = (first + last) // 2       if arr[mid]  key_element:          last = mid - 1       else:          return mid    return -1 arr = [20, 40, 60, 80, 100] key = 80 max_size = len(arr)result = iterative_binary(arr, max_size - 1, key)  if result != -1:     print("The element", key, "is present at index", (result), "in the position", (result + 1)) else:     print("The element is not present in the array")

Output

上述程序的输出如下:

The element 80  is found at the index 3 and in the position 4

这是二分搜索算法的工作原理。根据时间复杂度的概念,我们可以肯定二分搜索算法比线性搜索算法更高效,时间复杂度在其中起着重要的作用。通过使用这种类型的算法,可以搜索数组中的元素。尽管用于解决问题的过程不同,但结果不会波动。这是使用多种算法检查输出一致性的一个优点。

以上就是Python程序在数组中搜索元素的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1342906.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
Python – 实际订单索引距离
上一篇 2025年12月13日 05:59:33
如何在Python中找到对象的方法或属性?
下一篇 2025年12月13日 05:59:51

相关推荐

  • 在Xcelium/Specman环境中有效设置环境变量的指南

    本教程详细阐述了在xcelium/specman仿真环境中设置环境变量的多种策略,特别是针对从`e`代码调用外部python脚本的场景。内容涵盖了在仿真启动前通过shell设置、在`e`代码中为子进程构建命令以及利用tcl脚本等方法,旨在帮助用户理解环境变量的作用域并选择最合适的设置方式,确保外部工…

    2026年5月10日
    100
  • Python实现TXT文本数据转Excel:数值类型转换与平均值计算教程

    本教程详细指导如何使用Python和openpyxl库将TXT文本文件中的数据读取并写入Excel文件。内容涵盖了从文本数据中提取数值、将其转换为整数类型、在Excel中创建新工作表、逐行写入数据,以及动态计算并添加平均值列的全过程,确保数据类型准确无误。 1. 引言 在数据处理的日常工作中,我们经…

    2026年5月10日
    000
  • 解决树莓派4B上cv2导入错误的专业指南

    本文旨在解决树莓派4b上导入opencv (cv2) 库时遇到的`importerror: undefined symbol: __atomic_store_8`错误。我们将探讨两种解决方案:一种是临时的`ld_preload`环境变量设置,另一种是推荐的、更持久的从源代码重新编译opencv的方法…

    2026年5月10日
    000
  • Python的基础知识

    python:入门指南及第一个程序 Python以其易用性和强大的功能而闻名,广泛应用于网络开发、数据科学、人工智能和自动化等领域。无论是编程新手还是经验丰富的开发者,Python都是一个理想的选择。 安装Python 在开始编写Python代码之前,您需要先在系统上安装Python。 步骤一:下载…

    2026年5月10日
    000
  • PyInstaller打包应用时的数据文件依赖管理

    本文深入探讨了PyInstaller打包Python程序为可执行文件时,如何有效处理非脚本类数据文件(如文本文件、图片等)的依赖问题。核心解决方案是确保可执行文件与这些数据文件位于同一目录下,以保证程序能正确访问它们。文章将通过示例说明常见错误场景,并提供最佳实践,帮助开发者构建功能完整的独立应用。…

    2026年5月10日
    000
  • Python3多线程怎么实现_Python3多线程编程方法与实例解析

    多线程可提升Python程序效率,常用方法包括:1. threading模块创建线程;2. 继承Thread类自定义线程;3. 使用ThreadPoolExecutor管理线程池;4. 用Lock解决数据竞争;5. 通过Queue实现线程安全通信。 如果您希望在Python3中提升程序执行效率,通过…

    2026年5月10日
    000
  • Python3循环语句怎么用_Python3for和while循环使用技巧分享

    答案:Python中for循环用于遍历序列或固定次数执行,支持range()、enumerate()等操作;while循环基于条件持续运行,适用于未知次数的场景。 如果您在编写Python程序时需要重复执行某段代码,可以根据条件或序列来控制循环的执行。以下是关于Python3中for和while循环…

    2026年5月10日
    000
  • 在Python中动态嵌入变量到HTML iframe src属性的教程

    本教程详细阐述了如何在python中利用f-string(格式化字符串字面量)将python变量动态地嵌入到html的` 动态生成HTML与Python变量的融合 在Web开发或数据可视化场景中,我们经常需要根据Python程序中的数据动态生成HTML内容。一个常见的需求是将Python变量的值注入…

    2025年12月23日
    000
  • Python REST API数据清洗:利用模糊匹配识别姓名拼写变体与错别字

    本文探讨了在处理REST API数据时,如何有效识别并匹配因拼写错误或变体(如姓名)而导致的模糊数据。针对API通常不支持正则表达式进行复杂查询的限制,文章提出并详细介绍了使用Python的fuzzywuzzy库进行模糊匹配的解决方案。通过在客户端对获取的数据进行后处理,开发者可以灵活地处理不规范的…

    2025年12月22日
    000
  • 利用模糊匹配处理API数据中的名称拼写变体

    本文探讨了在通过REST API查询数据时,如何有效处理因拼写错误或名称变体导致的数据不一致问题。针对API通常不支持直接传递正则表达式进行模糊查询的限制,文章提出并详细介绍了使用Python的fuzzywuzzy库进行客户端模糊匹配的解决方案。通过实例代码,演示了如何获取数据后,在本地对名称字段进…

    2025年12月22日
    000
  • 如何监控程序内存使用 内存消耗分析工具介绍

    Linux工具如top、pmap可监控进程内存;2. Java可用jstat、jmap及MAT分析堆内存;3. Python推荐memory_profiler和tracemalloc;4. C/C++适用Valgrind和AddressSanitizer;应根据语言和环境选择合适工具,开发用精细工具…

    2025年12月18日
    000
  • XML的xml:space属性如何影响空白字符解析?

    xml中空白字符的默认行为是可被解析器删除或规范化;1. xml:space=”default”时,解析器可移除前导尾随空白、合并连续空白、删除纯空白文本节点;2. xml:space=”preserve”时,解析器必须保留所有空白字符,适用于代码、诗…

    2025年12月17日
    000
  • Python中模拟Go语言的Channel Select机制

    本文深入探讨了go语言中`select`语句的强大并发通信能力,并详细阐述了如何在python环境中,利用`threading`模块和`queue`数据结构,构建一个功能类似的通道选择机制。通过创建独立的监听线程将多个源队列的消息汇集到一个中心队列,python程序能够有效地等待并处理来自不同并发源…

    2025年12月16日
    000
  • 在Python中模拟Go语言的select并发模式

    python标准库中没有直接对应go语言`select`语句的并发原语。本文将探讨如何利用python的`threading`模块和`queue.queue`来实现类似go `select`的功能,即同时监听多个通信通道并处理首先就绪的事件。我们将通过逐步构建和优化代码示例,展示如何模拟go的“选择…

    2025年12月16日
    000
  • 优化Go程序I/O性能:从慢速fmt到高效bufio实践

    本文探讨了go程序在处理大量文件i/o时,为何可能出现低于预期的性能表现。通过实际案例分析,揭示了标准库fmt在直接文件操作时可能存在的效率瓶颈。教程详细介绍了如何利用bufio包进行缓冲i/o,并结合正确的格式化字符串和刷新机制,显著提升go程序的i/o处理速度,使其性能达到甚至超越python,…

    2025年12月16日
    200
  • Python与Go程序间共享变量的教程

    本文介绍如何在Python和Go程序之间共享变量。核心思路是利用标准流,Go程序将变量通过标准输出打印,Python程序则通过标准输入读取,实现跨语言的数据传递。本文将提供具体实现步骤和代码示例,帮助你理解和应用此方法。 利用标准流进行跨语言数据传递 在需要跨语言进行数据交互时,标准流(stdin,…

    2025年12月15日
    000
  • 如何在 Python 和 Go 语言之间共享变量

    本文将介绍如何在 Python 和 Go 语言编写的程序之间共享变量。Go 程序负责写入变量(例如字符串),而 Python 程序负责读取该变量。核心方法是利用标准输入输出流进行数据传递。 利用标准输入输出流共享变量 这种方法的核心思想是:Go 程序将需要共享的变量值通过标准输出 (stdout) …

    2025年12月15日
    000
  • Go语言在Windows平台上的开发与Python集成策略

    Go语言对Windows平台的支持已非常成熟,开发者可轻松在Windows环境下编译并运行Go程序。本文将详细介绍Go在Windows上的标准安装与编译流程,并探讨Python与Go之间实现高效通信的多种策略,包括基于网络协议的进程间通信(如RESTful API、gRPC)以及通过外部函数接口(F…

    2025年12月15日
    000
  • 如何用Go或Python获取手机通话记录?

    访问手机通话记录:技术途径与权限限制 想用Go或Python程序读取手机通话记录?这并非直接通过这些语言就能实现。Go和Python本身无法直接访问设备的底层数据。要实现这一目标,必须借助系统原生语言(如Android的Java/Kotlin或iOS的Swift/Objective-C)提供的API…

    2025年12月15日
    000
  • Python高效生成与存储大规模内存访问轨迹的实践指南

    本文旨在解决在python中为内存模拟器生成和存储大规模内存访问轨迹时遇到的性能与内存瓶颈。通过深入分析`print()`函数和内存存储的局限性,文章提出并详细阐述了直接利用文件写入流的高效策略。教程将提供示例代码,指导读者如何以指定格式(如`0x12345678 w`)高效地将数据写入文件,从而优…

    2025年12月15日
    000

发表回复

登录后才能评论
关注微信