zoukankan      html  css  js  c++  java
  • <Think Python>中斐波那契使用memo实现的章节

    If you played with the fibonacci function from Section 6.7, you might have noticed that
    the bigger the argument you provide, the longer the function takes to run. Furthermore,
    the run time increases very quickly.
    To understand why, consider Figure 11.2, which shows the call graph for fibonacci with
    n=4:
    A call graph shows a set of function frames, with lines connecting each frame to the frames
    of the functions it calls. At the top of the graph, fibonacci with n=4 calls fibonacci with
    n=3 and n=2. In turn, fibonacci with n=3 calls fibonacci with n=2 and n=1. And so on.
    Count how many times fibonacci(0) and fibonacci(1) are called. This is an inefficient
    solution to the problem, and it gets worse as the argument gets bigger.
    One solution is to keep track of values that have already been computed by storing them
    in a dictionary. A previously computed value that is stored for later use is called a memo.
    Here is an implementation of fibonacci using memos:

    known = {0:0, 1:1}
    def fibonacci(n):
      if n in known:
        return known[n]
      res = fibonacci(n-1) + fibonacci(n-2)
      known[n] = res
      return res

    known is a dictionary that keeps track of the Fibonacci numbers we already know. It starts
    with two items: 0 maps to 0 and 1 maps to 1.


  • 相关阅读:
    java 配置Apache,Tomcat的gzip压缩功能
    java并发编程中CountDownLatch和CyclicBarrier的使用
    Java常用工具包 Jodd
    Servlet 3特性:异步Servlet
    tomcat7安装
    2013-Hessian
    使用commons configuration管理配置文件
    2013-JVisualVM远程监听服务器内存进程
    Jquery复选框
    Jquery选择器总结
  • 原文地址:https://www.cnblogs.com/instona/p/3344742.html
Copyright © 2011-2022 走看看