def diy_sum(arr): if not arr: return 0 elif len(arr) == 1: return arr[0] else: return arr.pop(0) + diy_sum(arr) arr = [1, 2, 3] print(diy_sum(arr))
def count_elements(list): if not list: return None elif len(list) == 1: return 1 else: return 1 + count_elements(list[1:]) list = [1, 2, 3] print(count_elements(list))
def bigger(int1, int2):算法
if int1 >= int2: return int1 else: return int2
def find_biggest(list):函數
if not list: return None elif 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))
def binary_search_basic(list, target, low, high): if low > high: return None else: 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 = 3 print(binary_search_dc(list, target))