1. Function recursion
1. What is
a special form of nested call of function recursive function
refers specifically to calling itself in the process of calling a function, which is called function recursive call
def f1(): #在调用一个函数过程中直接调用自己
print('from f1')
f1()
2. Why use function recursion?
It will be more convenient and simple to use in certain situations
import sys
print(sys.getrecursionlimit()) #查看递归层级
sys.setrecursionlimit(2000) #改变递归层级
def f1(): #在调用一个函数过程中间接调用自己
print('fi')
f2()
def f2():
print('f2')
f1()
f1()
Meaningful recursion should be able to end under certain conditions.
The process of a recursion should be divided into two stages:
1. Backtracking: call to the next level.
2. Recursion: return to the next level.
Example
def age(n):
if n == 1:
return 18
return age(n-1) + 10
res = age(5)
print(res)
In what scenarios is recursion convenient?
Recursion is to use a function to implement a loop
example 1
nums = [1, [2, [3, [4, [5, [6, [7, [8, ]]]]]]]]
def func(nums):
for item in nums:
if type(item) is list:
func(item)
else:
print(item)
func([1, [2, [3, [4, [5, [6, [7, [8, ]]]]]]]])
Example 2 Find the number is not in the list
nums = [-3, 1, 5, 7, 9, 11, 13, 18, 22, 38, 78, 98]
方法一(效率不高)
for num in nums:
if num == find_num:
print('find it')
break
方法二(二分法,一种算法高效解决问题方法)
def search(find_num, nums):
# print(nums)
if len(nums) == 0:
print('not exists')
return
mid_index = len(nums) // 2
if find_num > nums[mid_index]:
# in the right
new_nums = nums[mid_index + 1:]
search(find_num, new_nums)
elif find_num < nums[mid_index]:
# in the left
new_nums = nums[:mid_index]
search(find_num, new_nums)
else:
print('find it')
search(23, nums)
Two, anonymous function
res=(lambda x,y:x+y)(4,5)
print(res)
Common usage is to use together with other functions for
example (find out the person with the most salary in the dictionary)
salaries = {
'axx':1000000,
'zxx':3000,
'egon':4000,
}
#介绍max print(max([1,2,3,4])) #max 传可迭代对象
def func(k): #只用一次可以用lambda代替
return salaries[k]
print(max(salaries,key=func)) #用key可以改变比较依据
print(max(salaries,key=lambda k:salaries[k]))
print(min(salaries,key=lambda k:salaries[k]))
print(sorted(salaries,key=lambda k:salaries[k]))
print(sorted(salaries,))
Three, built-in function to understand
filter # (filter)
names = ['egon_nb',"lxx_sb","hxx_sb"]
res =(name for name in names if name.endswith('sb'))
print(res)
res = filter(lambda name:name.endswith('sb'),names)
print(res)
print(list(res))
map #映出
names = ['egon','lxx','zxx']
res = [name + "vip" for name in names]
print(res)
res = map(lambda name:name + "vip",names)
print(res)
print(list(res))
reduce #The module is summarized as
from functools import reduce
reduce(lambda x,y:x+y,[1,2,3,4,5,6],100)
res = reduce(lambda x,y:x+y,["a","b","c"])
print(res)