I. recursive function
1) definition
- Calling function itself in function is recursion.
- The maximum depth of recursion in python is 1000, but the actual depth is less than 1000
def func():
print("-----func-----")
func()
func()
2) application
- You can use recursion to traverse various tree structures, such as folder system: you can use recursion to traverse all files in the folder
import os
def func(filepath, n):
files_list = os.listdir(filepath) # Get all files in the current folder
for file in files_list:
file_d = os.path.join(filepath, file) # Real path of splicing files
if os.path.isdir(file_d): # Recursive entry to determine whether the file is a folder
print("\t"*n, file)
func(file_d, n+1) #
else:
print("\t"*n, file) # Recursive export
2. Binary search
- Advantages: half of the data can be removed each time, and the search efficiency is high
- Requirement: the search sequence must be an ordered sequence
1) non recursive algorithm
a) use index
# Let the user enter a number n. Judge this n Whether it appears in lst in
lst = [4, 56, 178, 253, 625, 1475, 2580, 3574, 15963]
left = 0
right = len(lst) - 1
num = int(input("Please enter a number n: "))
while left <= right:
mid = (left + right) // 2
if lst[mid] > num:
right = mid - 1
elif lst[mid] < num:
left = mid + 1
else:
print("This number is in lst in")
break
else:
print("This number is not in lst in")
2) recursive algorithm
a) use index
# Let the user enter a number n. Judge this n Whether it appears in lst in
lst = [4, 56, 178, 253, 625, 1475, 2580, 3574, 15963]
def binary_search(lst, num, left, right):
if left > right:
return False
mid = (left + right) // 2
if lst[mid] > num:
right = mid - 1
return binary_search(lst, num, left, right)
elif lst[mid] < num:
left = mid + 1
return binary_search(lst, num, left, right)
else:return True
num = int(input("Please enter a number n: "))
ret = binary_search(lst, num, 0, len(lst)-1)
print(ret)
b) switch list
# Let the user enter a number n. Judge this n Whether it appears in lst in
lst = [4, 56, 178, 253, 625, 1475, 2580, 3574, 15963]
def binary_search(lst, num):
if len(lst) == 0:
return False
mid = (len(lst) - 1) // 2
if num > lst[mid]:
return binary_search(lst[mid+1:], num)
elif num < lst[mid]:
return binary_search(lst[:mid], num)
else:
print("This number is in lst in")
return True
num = int(input("Please enter a number n: "))
ret = binary_search(lst, num)
print(ret)