Home Backend Development Python Tutorial Python实现的数据结构与算法之基本搜索详解

Python实现的数据结构与算法之基本搜索详解

Jun 10, 2016 pm 03:14 PM
python search data structure algorithm

本文实例讲述了Python实现的数据结构与算法之基本搜索。分享给大家供大家参考。具体分析如下:

一、顺序搜索

顺序搜索 是最简单直观的搜索方法:从列表开头到末尾,逐个比较待搜索项与列表中的项,直到找到目标项(搜索成功)或者 超出搜索范围 (搜索失败)。

根据列表中的项是否按顺序排列,可以将列表分为 无序列表有序列表。对于 无序列表,超出搜索范围 是指越过列表的末尾;对于 有序列表,超过搜索范围 是指进入列表中大于目标项的区域(发生在目标项小于列表末尾项时)或者指越过列表的末尾(发生在目标项大于列表末尾项时)。

1、无序列表

在无序列表中进行顺序搜索的情况如图所示:

def sequentialSearch(items, target):
  for item in items:
    if item == target:
      return True
  return False
Copy after login

2、有序列表

在有序列表中进行顺序搜索的情况如图所示:

def orderedSequentialSearch(items, target):
  for item in items:
    if item == target:
      return True
    elif item > target:
      break
  return False
Copy after login

二、二分搜索

实际上,上述orderedSequentialSearch算法并没有很好地利用有序列表的特点。

二分搜索 充分利用了有序列表的优势,该算法的思路非常巧妙:在原列表中,将目标项(target)与列表中间项(middle)进行对比,如果target等于middle,则搜索成功;如果target小于middle,则在middle的左半列表中继续搜索;如果target大于middle,则在middle的右半列表中继续搜索。

在有序列表中进行二分搜索的情况如图所示:

根据实现方式的不同,二分搜索算法可以分为迭代版本和递归版本两种:

1、迭代版本

def iterativeBinarySearch(items, target):
  first = 0
  last = len(items) - 1
  while first <= last:
    middle = (first + last) // 2
    if target == items[middle]:
      return True
    elif target < items[middle]:
      last = middle - 1
    else:
      first = middle + 1
  return False
Copy after login

2、递归版本

def recursiveBinarySearch(items, target):
  if len(items) == 0:
    return False
  else:
    middle = len(items) // 2
    if target == items[middle]:
      return True
    elif target < items[middle]:
      return recursiveBinarySearch(items[:middle], target)
    else:
      return recursiveBinarySearch(items[middle+1:], target)
Copy after login

三、性能比较

上述搜索算法的时间复杂度如下所示:

搜索算法          时间复杂度
-----------------------------------
sequentialSearch      O(n)
-----------------------------------
orderedSequentialSearch  O(n) 
-----------------------------------
iterativeBinarySearch   O(log n)
-----------------------------------
recursiveBinarySearch   O(log n)
-----------------------------------
in             O(n)
Copy after login

可以看出,二分搜索 的性能要优于 顺序搜索

值得注意的是,Python的成员操作符 in 的时间复杂度是O(n),不难猜出,操作符 in 实际采用的是 顺序搜索 算法。

四、算法测试

#!/usr/bin/env python
# -*- coding: utf-8 -*-
def test_print(algorithm, listname, target):
  print(' %d is%s in %s' % (target, '' if algorithm(eval(listname), target) else ' not', listname))
if __name__ == '__main__':
  testlist = [1, 2, 32, 8, 17, 19, 42, 13, 0]
  orderedlist = sorted(testlist)
  print('sequentialSearch:')
  test_print(sequentialSearch, 'testlist', 3)
  test_print(sequentialSearch, 'testlist', 13)
  print('orderedSequentialSearch:')
  test_print(orderedSequentialSearch, 'orderedlist', 3)
  test_print(orderedSequentialSearch, 'orderedlist', 13)
  print('iterativeBinarySearch:')
  test_print(iterativeBinarySearch, 'orderedlist', 3)
  test_print(iterativeBinarySearch, 'orderedlist', 13)
  print('recursiveBinarySearch:')
  test_print(recursiveBinarySearch, 'orderedlist', 3)
  test_print(recursiveBinarySearch, 'orderedlist', 13)
Copy after login

运行结果:

$ python testbasicsearch.py
sequentialSearch:
 3 is not in testlist
 13 is in testlist
orderedSequentialSearch:
 3 is not in orderedlist
 13 is in orderedlist
iterativeBinarySearch:
 3 is not in orderedlist
 13 is in orderedlist
recursiveBinarySearch:
 3 is not in orderedlist
 13 is in orderedlist
Copy after login

希望本文所述对大家的Python程序设计有所帮助。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

See all articles