Saturday, January 24, 2015

cache_v2 = {} def fib_v2 (n): if n in (0, 1): return n if n in cache_v2: return cache_v2 insula [n]


We all know it Fibonacci sequence, the formula is very simple f (n) = f (n-1) + f (n-2), f (0) = 0, f (1) = 1 Fibonacci formula is handed back, Because you want to calculate f (n) and the need for the last results of the last calculation. Direct sets have the following function definition (in Python) def fib (n): if n in (0, 1): return n return fib (n-1) + fib (n-2) the actual test, you will find the top efficiency function is very poor, for example, we want to calculate f (5), sets of definitions, insula first calculate f (3) with f (4), but to calculate f (4) they must first know that f (3) with f (2), that is to say in fact, f (3) Well twice, and so on f (2) calculation of the three, if n is large, then, calculating f (n) will be repeated many unnecessary computations To solve this problem is not difficult, before joining in a cache in the function to record the counted value on it
cache_v2 = {} def fib_v2 (n): if n in (0, 1): return n if n in cache_v2: return cache_v2 insula [n] else: cache_v2 [n] = value = fib_v2 (n-1) + fib_v2 (n -2) return value above the red part of the code in order to use the additional cache code, here is another version, cache_v3 = {} def fib_v3 (n): if n in (0, 1): return n try: return cache_v3 [n] except KeyError: cache_v3 [n] = value = fib_v3 (n-1) + fib_v3 (n-2) return value
However, v2 and v3 version is not without drawbacks, compared with the original insula version of the fib (), the code is less direct, but also the need for additional space, the space required can be accessed at the local function declaration. Also, assume that we have a lot of similar fib () function need to use the cache to accelerate, it is difficult to modify one by one, we need to code it? This has laziness, impatience, and hubris three virtues of programmers is unbearable. Good practice is not to move to fib () as the real content, but the fib () as an object, insula and then another to write a function or class to handle fib (), use the syntax introduced in Python 2.4 Decorator up this purpose. I will introduce this syntax after the blog, please wait XD
Taiwan Military anthology
Python Idiom: Decorator II (passerby)
October, 2014
September, 2010
September, 2007
January, insula 2006


No comments:

Post a Comment