• Python:实现fibonacci斐波那契算法(附完整源码)


    Python:实现fibonacci斐波那契算法

    # fibonacci.py
    from math import sqrt
    from time import time
    
    
    def time_func(func, *args, **kwargs):
       
        start = time()
        output = func(*args, **kwargs)
        end = time()
        if int(end - start) > 0:
            print(f"{func.__name__} runtime: {(end - start):0.4f} s")
        else:
            print(f"{func.__name__} runtime: {(end - start) * 1000:0.4f} ms")
        return output
    
    
    def fib_iterative(n: int) -> list[int]:
     
        if n < 0:
            raise Exception("n is negative")
        if n == 0:
            return [0]
        fib = [0, 1]
        for _ in range(n - 1):
            fib.append(fib[-1] + fib[-2])
        return fib
    
    
    def fib_recursive(n: int) -> list[int]:
    
    
        def fib_recursive_term(i: int) -> int:
            """
            Calculates the i-th (0-indexed) Fibonacci number using recursion
            """
            if i < 0:
                raise Exception("n is negative")
            if i < 2:
                return i
            return fib_recursive_term(i - 1) + fib_recursive_term(i - 2)
    
        if n < 0:
            raise Exception("n is negative")
        return [fib_recursive_term(i) for i in range(n + 1)]
    
    
    def fib_memoization(n: int) -> list[int]:
    
        if n < 0:
            raise Exception("n is negative")
        # Cache must be outside recursuive function
        # other it will reset every time it calls itself.
        cache: dict[int, int] = {0: 0, 1: 1, 2: 1}  # Prefilled cache
    
        def rec_fn_memoized(num: int) -> int:
            if num in cache:
                return cache[num]
    
            value = rec_fn_memoized(num - 1) + rec_fn_memoized(num - 2)
            cache[num] = value
            return value
    
        return [rec_fn_memoized(i) for i in range(n + 1)]
    
    
    def fib_binet(n: int) -> list[int]:
    
        if n < 0:
            raise Exception("n is negative")
        if n >= 1475:
            raise Exception("n is too large")
        sqrt_5 = sqrt(5)
        phi = (1 + sqrt_5) / 2
        return [round(phi**i / sqrt_5) for i in range(n + 1)]
    
    
    if __name__ == "__main__":
        num = 20
        time_func(fib_iterative, num)
        time_func(fib_recursive, num)
        time_func(fib_memoization, num)
        time_func(fib_binet, num)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
  • 相关阅读:
    Sparse R-CNN 论文精读
    全渠道电商 | 国内知名的药妆要如何抓住风口实现快速增长?
    NLP之Bert多分类实现案例(数据获取与处理)
    支持向量机 (support vector machine,SVM)
    华清远见-html-js-jquery学习总结
    unittest自动测试多个用例时,logging模块重复打印解决
    RocketMQ(一)
    B站每日自动签到&传统单节点网站的 Serverless 上云
    eNsp使用技巧
    爬虫 Selector 选择器查找元素
  • 原文地址:https://blog.csdn.net/it_xiangqiang/article/details/126107815