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)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月13日 05:59:33
下一篇 2025年12月13日 05:59:51

相关推荐

  • 在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日
    000
  • 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
  • 深入理解Python列表在CSV文件中的写入机制

    当python列表通过`csv`模块写入csv文件时,它并不会以原生列表对象的形式存储。`csv`模块的默认行为是将所有非字符串数据类型隐式地通过`str()`函数转换为其字符串表示。这意味着一个python列表,包括其方括号和内部元素,将作为一个完整的文本字符串写入csv单元格,例如显示为`[&#…

    2025年12月15日
    000
  • Python Subprocess实时输出处理:原理、实践与优化

    本文深入探讨了python subprocess模块在处理子进程实时输出时遇到的常见延迟问题。核心在于子进程的输出缓冲机制,当其标准输出连接到管道而非终端时,会自动切换到块缓冲模式。文章提供了两种主要解决方案:在子进程中显式调用flush()方法或通过python -u参数禁用解释器缓冲。同时,强调…

    2025年12月15日
    200
  • Python条件判断:深入理解or运算符与in关键字在列表成员检测中的应用

    本文旨在解决Python条件判断中常见的逻辑错误,尤其是在验证用户输入是否匹配多个预设选项时。我们将详细解释`or`逻辑运算符的正确用法,并介绍更简洁、高效的`in`关键字,用于对列表等集合进行成员检测。通过实际代码示例,本教程将指导读者构建健壮的输入验证机制,确保程序仅处理有效数据,从而显著提升代…

    2025年12月15日
    000
  • 在Markdown中集成Python数据:动态内容生成指南

    本文旨在解决如何在Markdown文档中动态展示Python程序生成的数据,而非简单地简单地显示代码块。我们将探讨两种主要方法:一是通过Python程序结合模板引擎(如Jinja2)动态生成Markdown文件,适用于需要更新`README.md`等静态文档的场景;二是利用文学编程工具(如Pweav…

    2025年12月15日
    000
  • Python多线程:高效获取最快完成任务的结果

    本教程旨在解决python多线程编程中,如何启动多个并发任务并仅获取其中最快完成任务的结果,同时忽略其他耗时较长的任务。我们将深入探讨`concurrent.futures`模块,特别是`threadpoolexecutor`和`as_completed`方法,演示如何简洁高效地实现这一目标,从而优…

    2025年12月14日
    000
  • python继承是什么?

    继承允许子类获取父类的属性和方法,实现代码重用与功能扩展;子类可重写方法并用super()调用父类方法,支持多层及多重继承,按MRO顺序解析同名方法,提升代码组织性与灵活性。 Python继承是一种面向对象编程的机制,允许一个类(子类)获取另一个类(父类)的属性和方法。通过继承,可以复用已有代码,减…

    2025年12月14日
    000
  • Python浮点数精度与表示:深入理解截断与科学计数法

    本文深入探讨Python浮点数在处理大数字和特定小数位时出现的精度问题及表示行为。我们将解析IEEE 754浮点标准、Python `float.__repr__`的优化机制,以及为何看似“截断”或转换为科学计数法的现象实则是底层浮点表示的固有特性。文章将提供示例并介绍如何使用`decimal`模块…

    2025年12月14日
    000

发表回复

登录后才能评论
关注微信