1
1

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の高速フィボナッチ

Last updated at Posted at 2019-12-04

こうです(lru_cacheをつかって)

from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n):
    if n <= 1:
        return 1
    return fib(n - 2) + fib(n - 1)

こうです(自作キャッシュでメモ化して)

def fib(n):
    cache = {}
    def impl(ni):
        nonlocal cache
        if ni <= 1:
            return 1
        if ni not in cache:
            cache[ni] = impl(ni - 2) + impl(ni - 1)
        return cache[ni]
    return impl(n)

@shiracamusさんからのコメントを元に少し変更したもの↓

def fib(n, cache={0:1, 1:1}):
    if n not in cache:
        cache[n] = fib(n - 2) + fib(n - 1)
    return cache[n]

⚠️これは遅いです⚠️

def fib(n):
    if n <= 1:
        return 1
    return fib(n - 2) + fib(n - 1)
1
1
2

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?