python基础8:递归、作用域、匿名函数、函数式编程
递归
特点:
1)自己调用自己
2)有结束条件
3)每次进入更深一层递归时,问题规模相比上次递归都应有所减少
4)次数过多会导致内存溢出
例:
1 name = ["a1", "a2", "a3", "a4"] 2 3 def ask_way(): 4 if len(name) == 0: 5 return "ask over" 6 name_res = name.pop(0) 7 print(name_res) 8 if name_res == "a3": 9 return "asked the right way" 10 res = ask_way() 11 return res 12 13 res1 = ask_way() 14 print(res1)
作用域:
函数的运行和之前申明的作用域有关,和调用位置没有关系
例:
1 name = "ABC" 2 def test1(): 3 name = "123" 4 def test2(): 5 name = "mnb" 6 def test3(): 7 print(name) 8 return test3 9 return test2 10 11 print(test1()) 12 print(test1()()) 13 print(test1()()()) 14 print("-"*30) 15 test2 = test1() 16 print(test2) 17 test3 = test2() 18 print(test3) 19 print(test3()) 20 #输出结果: 21 ''' 22 <function test1.<locals>.test2 at 0x000001271233A8B0> 23 <function test1.<locals>.test2.<locals>.test3 at 0x000001271233A4C0> 24 mnb 25 None 26 ------------------------------ 27 <function test1.<locals>.test2 at 0x000001271233A8B0> 28 <function test1.<locals>.test2.<locals>.test3 at 0x000001271233A4C0> 29 mnb 30 None 31 '''
匿名函数:
lambda x,y:z = x+y
1 fun1 = lambda x,y:x+y 2 print(fun1(1,2)) 3 ''' 4 3 5 '''
补充:
编程方式:
面向过程编程
函数式编程
面向对象编程
函数式编程:
1、用编程语言去实现数学函数
2、不可保存变量状态,不修改变量
3、传入的参数为函数
1 def foo(x): 2 print(x) 3 def bar(y): 4 print(y) 5 6 foo(bar("ABC")) 7 #输出结果: 8 ''' 9 ABC 10 None 11 '''
4、返回值为函数:
例:
1 def bar(): 2 print(123) 3 4 def foo(): 5 print(456) 6 return bar 7 8 n = foo() 9 print(n) 10 n() 11 #输出结果: 12 ''' 13 456 14 <function bar at 0x00000248B03000D0> 15 123 16 '''
满足3、4任意一条即为高阶函数
递归优化:尾调用

浙公网安备 33010602011771号