[ Python ] 递归函数

一、 什么是递归函数

    如果一个函数在内部调用自身本身,这个函数就是递归函数。
    在递归函数中,是一个有去有回的过程。

 

二、递归函数的说明

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def fact(n):
        if n == 1:
                return 1
        return n * fact(n - 1)
 
print(fact(5))
 
# fact(5)
# ===> 5 * fact(4)
# ===> 5 * (4 * fact(3))
# ===> 5 * (4 * (3 * fact(2)))
# ===> 5 * (4 * (3 * (2 * fact(1))))
# ===> 5 * (4 * (3 * (2 * 1)))
# ===> 5 * (4 * (3 * 2))
# ===> 5 * (4 * 6)
# ===> 5 * 24
# ===> 120

 

    通过上面的实例,可以总结出:
        递归函数就是在函数内部调用自身本身,直到自身返回的是一个具体的值而不是函数,然后从内向外逐一返回函数的值,因此递归是一个有去有回两个过程组成的;

 

三、一个递归函数的实例

复制代码
menu = {
        '陕西省': {
                '西安':{
                        '未央区':{},
                        '莲湖区':{},
                        '高新区':{},
                },
                '咸阳':{
                        '秦都区':{},
                        '渭城区':{}
                }
        },
        '四川省': {
                '成都':{
                        '锦江区':{},
                        '青羊区':{},
                        '金牛区':{},
                },
                '绵阳':{
                        '涪城区': {},
                        '游仙区': {},
                }
        }
}

def threeTL(dic):
        while True:
                for key in dic: print(key)
                choice = input('>>>').strip()
                if choice == 'b' or choice == 'q': return choice
                elif choice in dic and dic[choice]:
                        res = threeTL(dic[choice])
                        if res == 'q': return 'q'
                elif not choice or choice not in dic:
                        continue

threeTL(menu)
menu_three.py
复制代码

 

 

该实例是选择省打印城市,输入城市打印区, 当用户输入 b 返回上一层,当用户输入 q 退出整个程序,这里最难理解的就是 b 和 q 的用法;

 

分析如下:

(1)正常递归深入过程:

复制代码
# def threeTL(dic):
#     while True:
#         for key in dic: print(key) # 陕西省、四川省
#         choice = input('>>>').strip()   # 用户输入:陕西省
#         if choice == 'b' or choice == 'q': return choice
#         elif choice in dic and dic[choice]:
#             res = threeTL(dic[choice])  # 递归返回 threeTL(dic['陕西省'])
#             if res == 'q': return 'q'
#         elif not choice or choice not in dic:
#             continue
#
# def threeTL(dic): # dic = dic['陕西省']
#     while True:
#         for key in dic: print(key) # 西安、咸阳
#         choice = input('>>>').strip()   # 用户输入:西安
#         if choice == 'b' or choice == 'q': return choice
#         elif choice in dic and dic[choice]:
#             res = threeTL(dic[choice])  # 递归返回 threeTL(dic['陕西省']['西安'])
#             if res == 'q': return 'q'
#         elif not choice or choice not in dic:
#             continue
#
# def threeTL(dic): # dic = dic['陕西省']['西安']
#     while True:
#         for key in dic: print(key) # 未央莲湖高新
#         choice = input('>>>').strip()   # # 用户输入:未央区
#         if choice == 'b' or choice == 'q': return choice
#         elif choice in dic and dic[choice]:
#             res = threeTL(dic[choice])  
#             if res == 'q': return 'q'
#         elif not choice or choice not in dic: # 因为未央区没有值,进入下一次循环
正常递归深入过程
复制代码

 

 

1
2
3
4
threeTL(menu)
-->threeTL(menu['陕西省'])
-->threeTL(menu['陕西省'])-->threeTL(menu['陕西省']['西安'])
-->threeTL(menu['陕西省'])-->threeTL(menu['陕西省']['西安'])-->threeTL(menu['陕西省']['西安']['未央区'])

 

(2)当用户输入 ' b ':

复制代码
def threeTL(dic): # dic = dic['陕西省']['西安']
        while True:
                for key in dic: print(key) # 未央莲湖高新
                choice = input('>>>').strip()   # # 用户输入:b
                if choice == 'b' or choice == 'q': return choice # 返回'b',程序退出
                elif choice in dic and dic[choice]:
                        res = threeTL(dic[choice])  
                        if res == 'q': return 'q'
                elif not choice or choice not in dic:
                        continue

def threeTL(dic): # dic = dic['陕西省']
        while True:
                for key in dic: print(key) # 第二次while循环打印 <西安、咸阳>(第一次while循环是在递归函数深入的时候执行)
                choice = input('>>>').strip()   # 第二次while循环到此,用户输入 b
                if choice == 'b' or choice == 'q': return choice # 返回'b',程序退出
                elif choice in dic and dic[choice]:
                        res = threeTL(dic[choice])  # res = 'b', 本次if循环没有匹配到res退出,进行下一次while循环
                        if res == 'q': return 'q'
                elif not choice or choice not in dic:
                        continue

def threeTL(dic):
        while True:
                for key in dic: print(key) # 第二次while循环打印 <陕西省、四川省>(第一次while循环是在递归函数深入的时候执行)
                choice = input('>>>').strip()   # 第二次while循环到此,用户输入 b
                if choice == 'b' or choice == 'q': return choice # 返回'b',整个程序退出,递归结束
                elif choice in dic and dic[choice]:
                        res = threeTL(dic[choice])  # 递归返回 threeTL(dic['陕西省'])
                        if res == 'q': return 'q'
                elif not choice or choice not in dic:
                        continue
输入'b',代码执行过程
复制代码

 

 

(3)当用户输入 'q'

复制代码
def threeTL(dic): # dic = dic['陕西省']['西安']
        while True:
                for key in dic: print(key) # 未央莲湖高新
                choice = input('>>>').strip()   # # 用户输入:q
                if choice == 'b' or choice == 'q': return choice # 返回'q',程序退出
                elif choice in dic and dic[choice]:
                        res = threeTL(dic[choice])  
                        if res == 'q': return 'q'
                elif not choice or choice not in dic:
                        continue

def threeTL(dic): # dic = dic['陕西省']
        while True:
                for key in dic: print(key) # <西安、咸阳>
                choice = input('>>>').strip()    
                if choice == 'b' or choice == 'q': return choice 
                elif choice in dic and dic[choice]:
                        res = threeTL(dic[choice])  # res = 'q'
                        if res == 'q': return 'q'    # 匹配到 res='q' 返回 'q' 程序退出
                elif not choice or choice not in dic:
                        continue

def threeTL(dic): # dic = dic['陕西省']['西安']
        while True:
                for key in dic: print(key) # 未央莲湖高新
                choice = input('>>>').strip()   # # 用户输入:q
                if choice == 'b' or choice == 'q': return choice # 返回'q',程序退出
                elif choice in dic and dic[choice]:
                        res = threeTL(dic[choice])  
                        if res == 'q': return 'q'
                elif not choice or choice not in dic:
                        continue
输入'q',代码执行过程
复制代码

 

本文作者:hukey

本文链接:https://www.cnblogs.com/hukey/p/9336233.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   hukey  阅读(172)  评论(0编辑  收藏  举报
编辑推荐:
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
阅读排行:
· 用 DeepSeek 给对象做个网站,她一定感动坏了
· DeepSeek+PageAssist实现本地大模型联网
· 手把手教你更优雅的享受 DeepSeek
· 腾讯元宝接入 DeepSeek R1 模型,支持深度思考 + 联网搜索,好用不卡机!
· 从 14 秒到 1 秒:MySQL DDL 性能优化实战
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起
  1. 1 彩虹 Jay
彩虹 - Jay
00:00 / 00:00
An audio error has occurred.

彩虹 + 轨迹 (Live) - 周杰伦 (Jay Chou)

彩虹

词:周杰伦

曲:周杰伦

哪里有彩虹告诉我

哪里有彩虹告诉我

能不能把我的愿望还给我

能不能把我的愿望还给我

为什么天这么安静

为什么天这么安静

所有的云都跑到我这里

有没有口罩一个给我

有没有口罩一个给我

释怀说了太多就成真不了

释怀说了太多就成真不了

也许时间是一种解药

也许时间是一种解药

也是我现在正服下的毒药

也是我现在正服下的毒药

看不见你的笑 我怎么睡得着

看不见你的笑 我怎么睡得着

你的声音这么近我却抱不到

你的声音这么近我却抱不到

没有地球太阳还是会绕

没有地球太阳还是会绕

没有理由我也能自己走

没有理由我也能自己走

你要离开 我知道很简单

你要离开 我知道很简单

你说依赖 是我们的阻碍

你说依赖 是我们的阻碍

就算放开 但能不能别没收我的爱

就算放开 但能不能别没收我的爱

当作我最后才明白

当作我最后才明白

看不见你的笑 要我怎么睡得着

看不见你的笑 要我怎么睡得着

你的声音这么近我却抱不到

没有地球太阳还是会绕 会绕

没有理由我也能自己走掉

释怀说了太多就成真不了

也许时间是一种解药 解药

也是我现在正服下的毒药

轨迹

词:黄俊郎

曲:周杰伦

我会发着呆然后忘记你

接着紧紧闭上眼

想着哪一天 会有人代替

想着哪一天 会有人代替

让我不再想念你

我会发着呆 然后微微笑

我会发着呆 然后微微笑

接着紧紧闭上眼

又想了一遍 你温柔的脸

又想了一遍 你温柔的脸

在我忘记之前