caching for when functools.cache() is not available (looking at you, pypy!)

This commit is contained in:
Stefan Harmuth 2021-12-21 10:08:18 +01:00
parent 898d4a8d85
commit fa68aa6109
2 changed files with 20 additions and 9 deletions

View File

@ -1,5 +1,5 @@
import math
from typing import Dict
from .tools import cache
def factorial(n: int) -> int:
@ -10,7 +10,8 @@ def factorial(n: int) -> int:
return math.factorial(n)
def fibonacci(n: int, cache: Dict[int, int] = None) -> int:
@cache
def fibonacci(n: int) -> int:
"""
F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1
0, 1, 1, 2, 3, 5, 8, 13, 21, ...
@ -18,13 +19,7 @@ def fibonacci(n: int, cache: Dict[int, int] = None) -> int:
if n < 2:
return n
if cache is None:
cache = {}
if n not in cache:
cache[n] = fibonacci(n - 1, cache) + fibonacci(n - 2, cache)
return cache[n]
return fibonacci(n - 1) + fibonacci(n - 2)
def triangular(n: int) -> int:

View File

@ -2,6 +2,7 @@ import datetime
import inspect
import os.path
import sys
from functools import wraps
from typing import Any
@ -42,3 +43,18 @@ def human_readable_time_from_delta(delta: datetime.timedelta) -> str:
time_str += "00:"
return time_str + "%02d" % (delta.seconds % 60)
def cache(func):
saved = {}
@wraps(func)
def newfunc(*args):
if args in saved:
return saved[args]
result = func(*args)
saved[args] = result
return result
return newfunc