• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
武纪亨
博客园    首页    新随笔    联系   管理    订阅  订阅
python函数进阶

内容概要

  • 递归函数
  • 算法(二分法)
  • 三元表达式
  • 列表生成式 字典生成式
  • 匿名函数

内容详细

"""
递归:函数在运行过程中 直接或简介的调用了自身
"""

# 官网表示:python默认的最大递归深度为1000次
# import sys
# print(sys.getrecursionlimit())
# print(sys.setrecursionlimit(2000))
# count = 1
# def index():
#     global count
#     count += 1
#     print(count)
#     print('from count')
#     index()
# index()

# def index():
#     print('from index')
#     func()
# def func():
#     print('from func')
#     index()
# func()  # 最多递归1000次

"""
递归
	1.递推
		一层层往下推导答案(每次递归之后赋值度相较于上一次一定有所下降)
	2.回溯
		依据最后的结论往后推导出最初需要的答案
	递归一定要有结束条件!!!
"""

# 伪代码:可能无法运行 但是可以表述逻辑
# age(5) = age(4) + 2
# age(4) = age(3)+2
# age(3) = age (2)+2
# age(2) = age(1)+2
# age = 18

# def get_name(n):
#     if n == 1:
#         return 18
#     return get_name(n - 1) + 2
# print(get_name(5))  # 26

# l = [1,[2,[3,[4,[5,[6,[7,[8,[9,[10,[11,[12,[13,[14,]]]]]]]]]]]]]]
# 打印出列表中每一个元素(列表除外)
# 1.循环该列表 获取列表内每一个元素
# 2.判断该元素是否是数字 如果是数字 则直接打印
# 3.如果是列表 则循环该列表 获取列表内每一个元素
# 4.判断该元素是否是数字 如果是数字 则直接打印
# 5.如果是列表 则循环该列表 获取列表内每一个元素
# 6.判断该元素是否是数字 如果是数字 则直接打印
# 7.如果是列表 则循环该列表 获取列表内每一个元素
# def get_num(l):
#     for i in l:
#         if type(i) is int:
#             print(i)
#         else:
#             get_num(i)
# get_num(l)  # 1 2 3 4 5 6 7 8 9 10 11 12 13 14

算法之二分法

# 什么是算法
	解决问题的高效方法
    
# 二分法(入门级别:还有一定距离)
# 第一种方式:直接for循环从左到右一次查找
	def get_num(l):
    for i in l:
        if type(i) is int:
            print(i)
    else:
        get_num(i)
get_num(l)  # 11, 23, 43, 57, 68, 76, 81, 99, 123, 321, 432, 567, 666, 712, 899999, 1111

# 第二种方式 二分法
"""
二分法能够使用的场景 数据集必须有序
"""
# def my_partner(target_num,l):
#     if len(l) == 0:
#         print('不好意思 我尽力了 没找到')
#         return
#     middle_index = len(l)//2
#     if target_num > l[middle_index]:
#         l_right = l[middle_index+1:]
#         print(l_right)
#         my_partner(target_num,l_right)
#     elif target_num < l[middle_index]:
#         l_left = l[:middle_index]
#         print(l_left)
#         my_partner(target_num,l_left)
#     else:
#         print('找到了',target_num)
# my_partner(444, l)  # 不好意思 我尽力了 没找到
# my_partner(11,l)  # 找到了 11

三元表达式

# def my_max(a,b):
#     if a>b:
#         return a
#     else:
#         return b
# """
# 当功能需求仅仅是二选一的情况下 name推荐使用三元表达式
# """
# def my_max(a,b):
#     return a if a > b else b
# print(my_max(1, 2))  # 2
"""
条件成立采用if前面的值 if条件 else 条件不成立采用else后面的值
三元表达式尽量不要嵌套使用
"""
# res = '干饭' if 10 > 2 else '不干饭'
# print(res)  # 干饭
# res = '干饭' if 10 > 20 else ('管饭' if 10 < 20 else '不管饭')
# print(res) # 管饭

# is_free = input('电影是否收费(y/n):').strip()
# res = '收费' if is_free == 'y' else '免费'
# print(res)  # 输入'y' 收费  输入'n' 免费

# username = input('请输入你的名字:').strip()
# res = 'NB' if username == 'jason' else 'DSB'
# print(res)  # 输入'jason' 'NB'  输入其他 'DSB'

列表生成式

# name_list = ['jason', 'kevin', 'tony', 'jerry']
# 给列表中所有的人名加上_DSB后缀
"""传统做法"""
# 1.先定义一个空列表 存放修改后的名字
# new_list = []
# 2.循环列表内的姓名
# for name in name_list:
# 3.生成新的名字
#     name = '%s_dsb'%i
# 4.把新生成的名字添加到新的列表里
#     new_list.append(name)
# print(new_list)  # ['jason_dsb', 'kevin_dsb', 'tony_dsb', 'jerry_dsb']
'''列表生成式'''
# res = ['%s_dsb' % name for name in name_list]
# print(res)  # ['jason_dsb', 'kevin_dsb', 'tony_dsb', 'jerry_dsb']


# name_list = ['jason', 'kevin', 'tony', 'jerry']
# 除了'jason',剩余名字后面加_dsb
# 传统做法 先定义一个空列表
# new_list = []
# for name in name_list:
#     if name == 'jason':
#         continue
#     else:
#         new_name = '%s_dsb'%name
#         new_list.append(new_name)
# print(new_list)  # ['kevin_dsb', 'tony_dsb', 'jerry_dsb']

'''列表生成式'''
# res = ['%s_dsb'%name for name in name_list if name != 'jason']
# print(res)  # ['kevin_dsb', 'tony_dsb', 'jerry_dsb']

字典生成式

# l1 = ['name','age','hobby']
# l2 = ['jason','18','read']
# # 1.先定义一个空字典
# new_dic = {}
# # 2. 循环l1的元素
# for i in range(len(l1)):
#     # 3.利用索引取值 得到KV值
#     new_dic[l1[i]] = l2[i]
# print(new_dic)  # {'name': 'jason', 'age': '18', 'hobby': 'read'}

# count = 0
# for i in l1:
#     print(count,i)
#     count += 1

# 枚举
'''
enumerate(l1)
	针对该方法使用for循环取值 每次会产生两个结果
		第一个是从0开始的数字
		第二个是被循环对象里面的元素
	还可以通过start参数控制起始位置
'''
# for i,j in enumerate(l1):
#     print(i,j)

# name_list = ['jason','kevin','tony','jerry']
# res = {i:j for i ,j in enumerate(name_list) if j != 'jason'}
# print(res)  # {1: 'kevin', 2: 'tony', 3: 'jerry'}
# 
# res1 = {i for i,j in enumerate(name_list)}
# print(res1,type(res1))  #{0, 1, 2, 3} <class 'set'>
# 
# # 迭代器
# res2 = (i for i,j in enumerate(name_list))
# print(res2)

匿名函数

# 匿名函数:没有名字的函数
'''
语法格式
	lambda 形参:返回值	
'''
# print(lambda  x:x**2)
# def index():
#     pass
# print(index)
# print((lambda  x:x**2)(2))
# res = lambda  x:x**2
# print(res(2))

 '''匿名函数一般不会单独使用 都是配合其他函数一起使用'''
# # map() # 映射
# l = [1,2,3,4,5,6,7,8,9]
# def index(n):
#     return n **2
# print(list(map(index,l)))  # [1, 4, 9, 16, 25, 36, 49, 64, 81]

posted on 2021-11-18 22:00  Henrywuovo  阅读(51)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3