search
HomeBackend DevelopmentPython TutorialWhat is recursion in python? Implementation of two priority search algorithms (code example)

 本篇文章给大家带来的内容是介绍python什么是递归?两种优先搜索算法的实现 (代码示例)。有一定的参考价值,有需要的朋友可以参考一下,希望对你们有所帮助。

 一、递归原理小案例分析

(1)# 概述

递归:即一个函数调用了自身,即实现了递归 凡是循环能做到的事,递归一般都能做到!

(2)# 写递归的过程

1、写出临界条件

2、找出这一次和上一次关系

3、假设当前函数已经能用,调用自身计算上一次的结果,再求出本次的结果

(3)案例分析:求1+2+3+...+n的数和

# 概述
'''
递归:即一个函数调用了自身,即实现了递归
凡是循环能做到的事,递归一般都能做到!

'''

# 写递归的过程
'''
1、写出临界条件
2、找出这一次和上一次关系
3、假设当前函数已经能用,调用自身计算上一次的结果,再求出本次的结果
'''

# 问题:输入一个大于1 的数,求1+2+3+....
def sum(n):
    if n==1:
        return 1
    else:
        return n+sum(n-1)

n=input("请输入:")
print("输出的和是:",sum(int(n)))

'''
输出:
请输入:4
输出的和是: 10
'''

#__author:"吉*佳"
#date: 2018/10/21 0021
#function:

import os
def  getAllDir(path):
    fileList = os.listdir(path)
    print(fileList)
    for fileName in fileList:
        fileAbsPath = os.path.join(path,fileName)
        if os.path.isdir(fileAbsPath):
            print("$$目录$$:",fileName)
            getAllDir(fileAbsPath)
        else:
            print("**普通文件!**",fileName)
    # print(fileList)
    pass

getAllDir("G:\\")

输出结果如下:

 二、深度遍历与广度遍历

(一)、深度优先搜索

说明:深度优先搜索借助栈结构来进行模拟

深度遍历示意图:

说明:

先把A压栈进去,在A出栈的同时把B C压栈进去,此时让B出栈的同时把DE压栈(C留着先不处理) 同理,在D出栈的时候,H I压栈,最后再从上往下

取出栈内还未出栈的元素,即达到深度优先遍历。

案例实践:利用栈来深度搜索打印出目录结构

程序代码:

#__author:"吉**"
#date: 2018/10/21 0021
#function:

# 深度优先遍历目录层级结构

import os

def getAllDirDP(path):
    stack = []
    # 压栈操作,相当于图中的A压入
    stack.append(path)

    # 处理栈,当栈为空的时候结束循环
    while len(stack) != 0:
        #从栈里取数据,相当于取出A,取出A的同时把BC压入
        dirPath = stack.pop()
        firstList = os.listdir(dirPath)
        #判断:是目录压栈,把该目录地址压栈,不是目录即是普通文件,打印
        for filename in firstList:
            fileAbsPath=os.path.join(dirPath,filename)
            if os.path.isdir(fileAbsPath):
                #是目录就压栈
                print("目录:",filename)
                stack.append(fileAbsPath)
            else:
                #是普通文件就打印即可,不压栈
                print("普通文件:",filename)



getAllDirDP(r'E:\[AAA](千)全栈学习python\18-10-21\day7\temp\dir')

结果:

该过程示意图解释:(s-05-1部分)

原理分析:

说明:

       队列是 先进先出的模型。A先进队,在A出队的时候,C B入队,按图示,C出队,FG 入队,B出队,DE入队,

F出队,JK入队,G出队,无入队,D出队,H I入队,最后E J K H I出队,均无入队了,即每一层一层处理、

故:先进先出的队列结构实现了广度优先遍历。 先进后出的栈结构实现的是深度优先遍历。

代码实现:

其实深度优先和广度优先在代码书写上是差别不大的,基本相同,只是一个是使用栈结构(用列表进行模拟)

另一个(广度优先遍历)是使用了队列的数据结构来达到先进先出的目的。

#__author:"吉**"
#date: 2018/10/21 0021
#function:

# 广度优先搜索模拟
# 利用队列来模拟广度优先搜索

import os
import collections

def getAllDirIT(path):
    queue=collections.deque()
    #进队
    queue.append(path)

    #循环,当队列为空,停止循环
    while len(queue) != 0:
        #出队数据 这里相当于找到A元素的绝对路径
        dirPath = queue.popleft()
        # 找出跟目录下的所有的子目录信息,或者是跟目录下的文件信息
        dirList = os.listdir(dirPath)

        #遍历该文件夹下的其他信息
        for filename in dirList:
            #绝对路径
            dirAbsPath = os.path.join(dirPath,filename)

            # 判断:如果是目录dir入队操作,如果不是dir打印出即可
            if os.path.isdir(dirAbsPath):
                print("目录:"+filename)
                queue.append(dirAbsPath)
            else:
                print("普通文件:"+filename)

# 函数的调用
getAllDirIT(r'E:\[AAA](千)全栈学习python\18-10-21\day7\temp\dir')

广度优先运行输出结构:

先图解:按照每一层从左到右遍历即可实现。

结束!

The above is the detailed content of What is recursion in python? Implementation of two priority search algorithms (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
How are arrays used in scientific computing with Python?How are arrays used in scientific computing with Python?Apr 25, 2025 am 12:28 AM

ArraysinPython,especiallyviaNumPy,arecrucialinscientificcomputingfortheirefficiencyandversatility.1)Theyareusedfornumericaloperations,dataanalysis,andmachinelearning.2)NumPy'simplementationinCensuresfasteroperationsthanPythonlists.3)Arraysenablequick

How do you handle different Python versions on the same system?How do you handle different Python versions on the same system?Apr 25, 2025 am 12:24 AM

You can manage different Python versions by using pyenv, venv and Anaconda. 1) Use pyenv to manage multiple Python versions: install pyenv, set global and local versions. 2) Use venv to create a virtual environment to isolate project dependencies. 3) Use Anaconda to manage Python versions in your data science project. 4) Keep the system Python for system-level tasks. Through these tools and strategies, you can effectively manage different versions of Python to ensure the smooth running of the project.

What are some advantages of using NumPy arrays over standard Python arrays?What are some advantages of using NumPy arrays over standard Python arrays?Apr 25, 2025 am 12:21 AM

NumPyarrayshaveseveraladvantagesoverstandardPythonarrays:1)TheyaremuchfasterduetoC-basedimplementation,2)Theyaremorememory-efficient,especiallywithlargedatasets,and3)Theyofferoptimized,vectorizedfunctionsformathematicalandstatisticaloperations,making

How does the homogenous nature of arrays affect performance?How does the homogenous nature of arrays affect performance?Apr 25, 2025 am 12:13 AM

The impact of homogeneity of arrays on performance is dual: 1) Homogeneity allows the compiler to optimize memory access and improve performance; 2) but limits type diversity, which may lead to inefficiency. In short, choosing the right data structure is crucial.

What are some best practices for writing executable Python scripts?What are some best practices for writing executable Python scripts?Apr 25, 2025 am 12:11 AM

TocraftexecutablePythonscripts,followthesebestpractices:1)Addashebangline(#!/usr/bin/envpython3)tomakethescriptexecutable.2)Setpermissionswithchmod xyour_script.py.3)Organizewithacleardocstringanduseifname=="__main__":formainfunctionality.4

How do NumPy arrays differ from the arrays created using the array module?How do NumPy arrays differ from the arrays created using the array module?Apr 24, 2025 pm 03:53 PM

NumPyarraysarebetterfornumericaloperationsandmulti-dimensionaldata,whilethearraymoduleissuitableforbasic,memory-efficientarrays.1)NumPyexcelsinperformanceandfunctionalityforlargedatasetsandcomplexoperations.2)Thearraymoduleismorememory-efficientandfa

How does the use of NumPy arrays compare to using the array module arrays in Python?How does the use of NumPy arrays compare to using the array module arrays in Python?Apr 24, 2025 pm 03:49 PM

NumPyarraysarebetterforheavynumericalcomputing,whilethearraymoduleismoresuitableformemory-constrainedprojectswithsimpledatatypes.1)NumPyarraysofferversatilityandperformanceforlargedatasetsandcomplexoperations.2)Thearraymoduleislightweightandmemory-ef

How does the ctypes module relate to arrays in Python?How does the ctypes module relate to arrays in Python?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo

See all articles

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

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function