1 函数的递归
函数的递归调用时函数嵌套调用的一种特殊形式,在调用的过程中又直接或者间接的调用了该函数
函数的递归调用必须有两个明确的阶段:
1 回溯:函数一次次的调用下去每一次调用,问题的规模都应该减少,在问题结束时要有明确的结束标志
2 递推:往回一次次推算出结果
递归调用案例:
二分法:
nums=[13,15,17,23,31,53,74,81,93,102,103,201,303,403,503,777] s= 503 def ef(nums,s): m_nums = len(nums) // 2 if s == nums[m_nums]: print('找到了') return if s>nums[m_nums]: nums = nums[m_nums+1:] ef(nums,s) elif s<nums[m_nums]: nums = nums[:m_nums] ef(nums,s) else: print('输入的值不存在!') ef(nums,13)
三元表达式:
print(1 if 2>1 else 2)
列表生成式:
l = ['1','2','3','4'] l_new = [i+'nihao' for i in l]
字典生成式:
new = ['老王','18','男'] new2 = ['name','age','sex'] dic = {new2:new[i] for i,new2 in enumerate(new2)}
匿名函数:(只用一次的函数)
(lambda x,y:x+y)(1,2)
匿名函数+内置函数:
max
dic = {'laowan':300, 'laozhou':400, 'laoliu ':500} res = max(dic,key=lambda name:dic[name]) print(res)
min
dic = {'laowan':300, 'laozhou':400, 'laoliu ':500} res = min(dic,key=lambda name:dic[name]) print(res)
sorted
l = [1,4,5,6,7,8,9,11,55,456,789,44] res = sorted(l,reverse=True) print(res)
map
l = [1,5,6,77,44,99,44] res = map(lambda sum:sum+3,l) res = list(res) print(res)
filter
l = ['abc1','bac1','dlc1','dfasdfa'] res= filter(lambda f:f.endswith('1'),l) res = list(res) print(res)
reduce
from functools import reduce l = ['a','b','c','d'] res = reduce(lambda x,y:x+y,l) print(res)