4-1 阶乘函数的递归实现
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
4-2 绘制一个标尺的函数的递归实现
def draw_line(tick_length, tick_label=''):
"""
Draw one line with given tick length(followed by optional label).
:param tick_length:
:param tick_label:
:return:
"""
line = '-'*tick_length
if tick_label:
line += ' ' + tick_label
print(line)
def draw_interval(center_length):
"""
Draw tick interval based ipon a central tick length.
:param center_length:
:return:
"""
if center_length > 0: # stop when length drops to 0
draw_interval(center_length - 1) # recursively draw top ticks
draw_line(center_length) # draw center tick
draw_interval(center_length - 1) # recursively draw bottom ticks
def draw_ruler(num_inches, major_length):
"""
Draw English ruler with given number of inches, major tick length.
:param num_inches:
:param major_length:
:return:
"""
draw_line(major_length, '0') # draw inch 0 line
for j in range(1, 1 + num_inches):
draw_interval(major_length - 1) # draw interior ticks for inch
draw_line(major_length, str(j)) # draw inch j line and label
if __name__ == '__main__':
draw_ruler(1, 5)
输出
----- 0
-
--
-
---
-
--
-
----
-
--
-
---
-
--
-
----- 1
4-3 二分查找算法的实现
import numpy as np
def binary_search(data, target, low, high):
"""
Return True if target is found in indicated portion of a Python list.
The search only considers the portion from data[low] to data[high] inclusive.
:param data:
:param target:
:param low:
:param middle:
:return:
"""
if low > high:
return False # interval us empty;no match
else:
mid = (low + high) // 2
if target == data[mid]:
return True
elif target < data[mid]:
# recur on the portion left of the middle
return binary_search(data, target, low, mid - 1)
else:
# recur on the portion right of the middle
return binary_search(data, target, mid + 1, high)
if __name__ == '__main__':
data = np.random.randint(1, 125, size=30, dtype=np.uint8)
print(data)
temp = sorted(data)
print(temp)
result = binary_search(temp, 4, 5, 25)
print(result)
count = 0
for i in range(500):
data = np.random.randint(1, 125, size=30, dtype=np.uint8)
temp = sorted(data)
if binary_search(temp, 4, 0, len(data)):
count += 1
print(count)