# 递归函数

### 函数的递归调用：

``````是函数嵌套调用的一种特殊形式。

``````
``````def f1():
print(‘from f1‘)
f1()
f1()
# 函数默认调用1000次

def f1():
print("f1")
f2() # 调用 f2()
def f2():
print(‘f2‘)
f1() # 调用 f1()
``````
``````# 更改函数调用次数
import sys
print(sys.getrecursionlimit()) # 输出 函数允许调用次数  1000
sys.setrecursionlimit(2000) # 设置函数的允许调用次数为2000
print(sys.getrecursionlimit()) # 2000
``````

### 递归的过程分为2个阶段：

``````1、回溯：向下一层一层调用
2、递推：向上一层一层返回
``````
``````def age(n):
if n == 1:
return 18
return age(n-1) + 10
res = age(5)
print(res) # 58
``````
``````# 输出列表中的所有值
nums = [1,[2,[3,[4,[5,[6,[7,[8]]]]]]]]
def fun(nums):
for i in nums:
if type(i) is list:
fun(i)
else:
print(i)
fun(nums)
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8

``````

### 二分法：

``````li = [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 18]

def find(find_number, li):
print(li)
if len(li) == 0:
print(‘值不存在列表中‘)
return
num = len(li) // 2
if li[num] < find_number:
new_li = li[num + 1:]
find(find_number, new_li)
elif li[num] > find_number:
new_li = li[:num]
find(find_number, new_li)
else:
print(‘找到了‘)

# find(9998,li)
# [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 18]
# [9, 10, 12, 15, 18]
# [9, 10]
# 找到了
``````

# 匿名函数

``````没有名字的函数，创建直接调用
``````

## lamada：

``````lambda x,y:x+y
f = lambda x,y:x+y
print(f(1,2)) # 3
res = (lambda x,y:x+y)(10,6)
print(res) # 16
``````
``````def name(n):
return lambda a:a+n
res = name(10)
print(res)  # <function name.<locals>.<lambda> at 0x000002E9990AA160>
print(res(10)) # 20
``````
``````dic = {
‘jon‘: 5000,
‘tom‘: 9000,
‘ali‘: 8000
}
max = max(dic, key=lambda k: dic[k])  # 求最大值,返回最大值名字
print(max)
min = min(dic, key=lambda k: dic[k])  # 求最小值,返回最大值名字
print(min)
sor = sorted(dic)  # 名字排序
print(sor)
sort = sorted(dic, key=lambda k: dic[k])  # 根据value排序名字
print(sort)
# tom
# jon
# [‘ali‘, ‘jon‘, ‘tom‘]
# [‘jon‘, ‘ali‘, ‘tom‘]
``````

## 了解：

### 1、filter

``````过滤 (迭代器)
name = [‘tom‘,‘jon‘,‘som‘]
res = [i for i in name if i.endswith(‘m‘)]
print(res) # [‘tom‘, ‘som‘]
res1 = filter(lambda name:name.endswith(‘m‘),name)
res1 = list(res1)
print(res1) # [‘tom‘, ‘som‘]

``````

### 2、map

``````映射
name = [‘tom‘,‘jon‘,‘som‘]
res = [ i + ‘ vip‘ for i in name]
print(res)
# [‘tom vip‘, ‘jon vip‘, ‘som vip‘]
res1 = map(lambda name:name + ‘ vip‘, name)
print(list(res1))
# [‘tom vip‘, ‘jon vip‘, ‘som vip‘]
``````

### 3、reduce

``````合并：可以合并数字也可以合并字符串
from functools import reduce
res = reduce(lambda x,y:x+y,[1,2,3,4])
print(res) # 10
res1 = reduce(lambda x,y:x+y,[‘a‘,‘b‘,‘c‘])
print(res1) # abc

``````

(0)
(0)

© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com