【算法入门-Python】02_递归

一、递归

递归的两个特点:调用自身;结束条件。

python 复制代码
def func1(x):
    print(x)
    func1(x-1)

没有结束条件,si递归。不是递归。

python 复制代码
def func2(x):
	if x > 0:
        print(x)
        func2(x+1)

递归调用的x+1,没有结束条件。不是递归

python 复制代码
def func3(x):
    if x > 0:
    	print(x)
        func3(x-1)

是递归。打印123

如下图:先打印,后递归。从上往下123

python 复制代码
def func4(x):
	if x > 0:
        func4(x-1)
        print(x)

func3一样,只是打印位置不同。是递归。打印321

如下图:先递归,后打印。从上往下321

递归实例:汉诺塔问题

问题:

思路:

第一步和第三步是原问题的一个子问题

python 复制代码
# a,b,c表示三个盘子,这里原函数表示:起点为a,经过b,移动到c
def hanoi(n, a, b, c): 
    if n > 0:
        hanoi(n-1, a, c, b)
        print("moving from %s to %s" % (a, c))
        hanoi(n-1, b, a, c)
        
# test
hanoi(3, 'A', 'B', 'C')

汉诺塔移动次数递推式:h(x) = 2h(x-1) + 1

相关推荐
千里马-horse4 小时前
Napi::Array
开发语言·array·napi
纪伊路上盛名在4 小时前
vscode的colab扩展目前的一些问题
ide·vscode·python·编辑器·colab·前后端
lly2024064 小时前
Julia 的复数和有理数
开发语言
春日见4 小时前
如何提升手眼标定精度?
linux·运维·开发语言·数码相机·matlab
宁大小白4 小时前
pythonstudy Day41
python·机器学习
AAA阿giao4 小时前
从树到楼梯:数据结构与算法的奇妙旅程
前端·javascript·数据结构·学习·算法·力扣·
盼哥PyAI实验室4 小时前
Python 爬虫核心基础:请求与响应机制全解析(从 GET 请求到 JSON 分页实战)
爬虫·python·json
Tipriest_4 小时前
Python 常用特殊变量与关键字详解
linux·python·关键字·特殊变量
Salt_07284 小时前
DAY 41 Dataset 和 Dataloader 类
python·算法·机器学习
古城小栈4 小时前
Java 响应式编程:Spring WebFlux+Reactor 实战
java·开发语言·spring