书中源码 第4章 递归

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值