Welcome, guest | Sign In | My Account | Store | Cart

Save each set of parameters with your respective return value in cache.

Python, 18 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Cache:
    def __init__(self):
        # cache of salf.fatorial()
        self.c_fatorial = {}
        
    def fatorial(self,  x):
        result = 0
        # first, verify in cache
        if x in self.c_fatorial.keys():
            return self.c_fatorial[x]
        # if not in cach, process
        if x <= 1:
            result = 1
        else:
            result = x * self.fatorial(x - 1)
        
        self.c_fatorial[x] = result # put the result in cache
        return result

2 comments

Abhishek Mishra 11 years, 4 months ago  # | flag

Here is why "if x in self.c_factorial.keys()" would slow your cache down - http://blog.ideamonk.in/2010/07/poorly-implementing-caching-in-python.html

"Fail early, fail fast" FTW.

Created by Danillo Souza on Tue, 27 Jul 2010 (GPL3)
Python recipes (4591)
Danillo Souza's recipes (3)

Required Modules

  • (none specified)

Other Information and Tasks