zoukankan      html  css  js  c++  java
  • 【数据结构】关于递归的几个例子

    # -*- coding: utf-8 -*-
    
    
    def factorial(n: int):
        if n == 0:
            return 1
        else:
            return n * factorial(n - 1)
    
    
    def draw_line(tick_length, tick_label=''):
        line = '-' * tick_length
        if tick_label:
            line += ' ' + tick_label
        print(line)
    
    
    def draw_interval(center_length):
        if center_length > 0:
            draw_interval(center_length - 1)
            draw_line(center_length)
            draw_interval(center_length - 1)
    
    
    def draw_ruler(num_inches, major_length):
        draw_line(major_length, '0')
        for j in range(1, 1 + num_inches):
            draw_interval(major_length - 1)
            draw_line(major_length, str(j))
    
    
    def binary_search(data, target, low, height):
        if low > height:
            return False
        else:
            mid = (low + height) // 2  # 先除后向下取整
            if target == data[mid]:
                return True
            if target < data[mid]:
                return binary_search(data, target, low, mid - 1)
            else:
                return binary_search(data, target, mid + 1, height)
    
    
    import os
    
    
    def disk_usage(path):
        total = os.path.getsize(path)
        if os.path.isdir(path):
            for filename in os.listdir(path):
                childpath = os.path.join(path, filename)
                total += disk_usage(childpath)
        print("{0:<7}".format(total), path)
        return total
    
    
    if __name__ == '__main__':
        # after_sort = quick_sort([1, 3, 0, 34, 32, 2, 13, 3])
        # print(after_sort)
    
        # 递归1, 阶乘
        # print(factorial(4))
        # 递归2,绘制英式标尺
        # draw_ruler(3, 3)
        # 递归3,二分查找
        # data = [2, 3, 4, 5, 67, 89, 91, 92]
        # print(binary_search(data, 89, 0, len(data) - 1))
        # 递归4,文件磁盘使用情况
        disk_usage("/Users/nidazhong/Downloads")
    
    “年轻时,我没受过多少系统教育,但什么书都读。读得最多的是诗,包括烂诗,我坚信烂诗早晚会让我邂逅好诗。” by. 马尔克斯
  • 相关阅读:
    增量学习中的自我训练
    半监督学习和直推学习的区别
    LeetCode: Word Break
    LeetCode: Linked List Cycle
    LeetCode: Reorder List
    LeetCode: Binary Tree Traversal
    LeetCode: LRU Cache
    LeetCode: Insertion Sort List
    LeetCode: Sort List
    LeetCode: Max Points on a Line
  • 原文地址:https://www.cnblogs.com/jzsg/p/11296205.html
Copyright © 2011-2022 走看看