《算法圖解》第四章第一節練習

4.1請編寫前述sum函數的代碼。

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))

4.2編寫一個遞歸函數來計算列表包含的元素數。

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))

4.3找出列表中最大的數字

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))

4.4 還記得第1章介紹的二分查找嗎?它也是一種分而治之算法。你能找出二分查找算法的基線條件和遞歸條件嗎?

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))

參考:
https://blog.csdn.net/XIAOZHI....net

相關文章
相關標籤/搜索