# 函数递归

·  阅读 819

## 函数递归介绍

``````def foo():
print('foo')
func()
def func():
print('func')
foo()

func()

'''

RecursionError: maximum recursion depth exceeded while calling a Python object(超过最大递归深度)
'''

``````def foo(n):
if n == 1:
print('递归结束')
return
else:
foo(n-1)
foo(2)

## 函数递归原理及使用

``````要想知道小一的苹果数量就需要知道小二的苹果数量，而小二的苹果数量又取决于小三，小三的苹果数量又是基于小四的苹果数量：
app_num(1) = app_num(2) + 1
app_num(2) = app_num(3) + 1
app_num(3) = app_num(4) + 1
app_num(4) = 2

app_num(4) = 2
app_num(x) = app_num(x+1) + 1

``````def apple_num(x):
if x == 4:  # 结束递归的条件
return 2
return apple_num(x+1) + 1

apple_num1 = apple_num(1)
print(apple_num1)  # 5

## Practice

``````list1 = [[[1, 2], [3, 4], [5, [6, 7], [8, 9, 10], 11, 12], 13]]

def func(items):
for elements in items:
if type(elements) is list:
func(elements)
else:
print(elements)
func(list1)

``````# 使用二分法：先取出列表的中间位置的值，与需要的数字进行比较，如果中间位置的值大于需要的值，那么就在中间值的左侧2 进行比较，如果小于，那么就在中间值的右侧进行比较，如果刚好等于，就输出值。然后对上述步骤进行循环

list1 = [0,2,5,7,9,11,34]
find_num = 2
def func(find_num,list1):
# 输出每次切分后生成的list1
print(list1)
mid_index = len(list1) // 2
if find_num > list1[mid_index]:
list1 = list1[mid_index+1:]
func(find_num,list1)
elif find_num < list1[mid_index]:
list1 = list1[:mid_index]
func(find_num,list1)
elif find_num == list1[mid_index]:
print(f'找到了{list1[mid_index]},索引为{mid_index}')
elif len(list1)  == 0:
print('不存在这个值')
return
func(find_num,list1)