caching for when functools.cache() is not available (looking at you, pypy!)
This commit is contained in:
parent
898d4a8d85
commit
fa68aa6109
@ -1,5 +1,5 @@
|
|||||||
import math
|
import math
|
||||||
from typing import Dict
|
from .tools import cache
|
||||||
|
|
||||||
|
|
||||||
def factorial(n: int) -> int:
|
def factorial(n: int) -> int:
|
||||||
@ -10,7 +10,8 @@ def factorial(n: int) -> int:
|
|||||||
return math.factorial(n)
|
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
|
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, ...
|
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:
|
if n < 2:
|
||||||
return n
|
return n
|
||||||
|
|
||||||
if cache is None:
|
return fibonacci(n - 1) + fibonacci(n - 2)
|
||||||
cache = {}
|
|
||||||
|
|
||||||
if n not in cache:
|
|
||||||
cache[n] = fibonacci(n - 1, cache) + fibonacci(n - 2, cache)
|
|
||||||
|
|
||||||
return cache[n]
|
|
||||||
|
|
||||||
|
|
||||||
def triangular(n: int) -> int:
|
def triangular(n: int) -> int:
|
||||||
|
|||||||
@ -2,6 +2,7 @@ import datetime
|
|||||||
import inspect
|
import inspect
|
||||||
import os.path
|
import os.path
|
||||||
import sys
|
import sys
|
||||||
|
from functools import wraps
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
@ -42,3 +43,18 @@ def human_readable_time_from_delta(delta: datetime.timedelta) -> str:
|
|||||||
time_str += "00:"
|
time_str += "00:"
|
||||||
|
|
||||||
return time_str + "%02d" % (delta.seconds % 60)
|
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
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user