【算法入门-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

相关推荐
ZhengEnCi17 分钟前
电脑操作 Agent 一直点不中:截图没更新时,提示词该怎么改才能停止瞎试
人工智能·python·agent
郝学胜-神的一滴1 小时前
Effective STL 条款09:慎重选择删除元素的方法
开发语言·网络·数据结构·c++·算法·stl
Wellijohn2 小时前
dict、tuple、dataclass 还是 slots?我把 6 种数据载体的 8 项开销全测了一遍
后端·python·性能优化
bufengwangluo3 小时前
爬虫和调用 API 有什么区别?为什么优先选 API
python·网络爬虫·ip·api调用
Dmz丶3 小时前
前端转 AI 100 天 Day 54:RAG 项目实战(三)——多轮对话 + 会话管理
python
console.log('npc')3 小时前
Python第9课 类学习笔记,前端js语法对照
前端·python·学习
geovindu5 小时前
python:Logistic Regression
开发语言·后端·python·算法
摇滚侠6 小时前
《On Java 中文版 基础卷》阅读笔记 内部类 21
java·开发语言·笔记