4.1请编写前述sum函数的代码。
def diy_sum(arr):if not arr: return 0elif len(arr) == 1: return arr[0]else: return arr.pop(0) + diy_sum(arr)arr = [1, 2, 3]print(diy_sum(arr))
4.2编写一个递归函数来计算列表包含的元素数。
def count_elements(list):if not list: return Noneelif len(list) == 1: return 1else: return 1 + count_elements(list[1:])list = [1, 2, 3]print(count_elements(list))
4.3找出列表中最大的数字
def bigger(int1, int2):
if int1 >= int2: return int1else: return int2
def find_biggest(list):
if not list: return Noneelif len(list) == 1: return list[0]elif len(list) == 2: return bigger(list[0], list[1])else: return bigger(list[0], find_biggest(list[1:]))list = [1, 5, 3, 2]print(find_biggest(list))
4.4 还记得第1章介绍的二分查找吗?它也是一种分而治之算法。你能找出二分查找算法的基线条件和递归条件吗?
def binary_search_basic(list, target, low, high):if low > high: return Noneelse: mid = int((low + high) / 2 + 0.5) guess = list[mid] if guess == target: return mid elif guess > target: high = mid - 1 return binary_search_basic(list, target, low, high) else: low = mid + 1 return binary_search_basic(list, target, low, high)def binary_search_dc(list, target): return binary_search_basic(list, target, 0, len(list) - 1)list = [1, 2, 3, 4, 5]target = 3print(binary_search_dc(list, target))
参考:
https://blog.csdn.net/XIAOZHI...