13
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonで再帰フィボナッチのメモ化

Posted at
# -*- coding: utf-8 -*-
def fib(n):
    """フィボナッチ数列"""
    if n <= 1:
        return n
    return fib(n-1) + fib(n-2)

def fib_memo(n):
    """メモ化フィボナッチ"""
    memo = [0]*(n+1)

    def _fib(n):
        if n <= 1:
            return n
        if memo[n] != 0:
            return memo[n]
        memo[n] = _fib(n-1) + _fib(n-2)
        return memo[n]

    return _fib(n)

時間計測

import time

def do_fib():
    start = time.time()
    print(fib(50))
    stop = time.time()
    print("elapsed: {}".format(stop - start))

def do_fib_memo():
    start = time.time()
    print(fib_memo(50))
    stop = time.time()
    print("elapsed: {}".format(stop - start))

if __name__ == '__main__':
    do_fib()
    do_fib_memo()
実行結果
12586269025
elapsed: 3211.8407917022705
12586269025
elapsed: 0.0009133815765380859
13
10
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?