最近看算法图解,对个别章节习题尝试作答,如果错误,欢迎指出
4.1 请编写前述sum函数的代码
def sum(a):
if len(a) == 0:
return 0
elif len(a) == 1:
return a[0]
else:
return a[0] + sum(a[1:])
val = sum([1,2,3,4,5,6,7,8,9,10])
print val
4.2 编写一个递归函数来计算列表包含的元素数
def count(list):
if len(list) == 0:
return 0
elif len(list) == 1:
return 1
else:
return 1 + count(list[1:])
val = count([1,2,3,4,5,6,7,8,9])
print val
4.3 找出列表中最大的数字
def bigger(v1, v2):
if v1 >= v2:
return v1
else:
return v2
def max(list):
if len(list) == 1:
return list[0]
elif len(list) == 2:
return bigger(list[0], list[1])
else:
return bigger(list[0], max(list[1:]))
val = max([1,2,103,4,5,16,7,8,9])
print val
4.4 还记得第1章介绍的二分查找吗?它也是一种分而治之算法。你能找出二分查找算法的基线条件和递归条件吗?
def binary_search_impl(list, item, low, high):
if low > high:
return None
else:
mid = (low + high) / 2
guess = list[mid]
if guess == item:
return mid
elif guess > item:
high = mid - 1
return binary_search_impl(list, item, low, high)
else:
low = mid + 1
return binary_search_impl(list, item, low, high)
def binary_search(list, item):
return binary_search_impl(list, item, 0, len(list)-1)
list = [1,3,5,7,9]
val = binary_search(list, 8)
print val