This decorator allows to optimize the calculus of some lists (with growing values, such as primes list) using previous executions.
Language: Python
- #our magic decorator
- class growing_limited_by_arg_mem_list:
- def __init__ (self, function):
- self.max = -1
- self.list = []
- self.function = function
- def __call__ (self, *args):
- n = args[0]
- if n > self.max:
- if self.max > 0:
- self.list = self.function (n, self.list)
- else:
- self.list = self.function (n)
- self.max = n
- return self.list
- else:
- a1 = 0
- a2 = len(self.list)
- i = 0
- while True:
- i = (a2+a1)/2
- current_pos = self.list[i]
- if current_pos == n or ( current_pos < n and self.list[i+1] > n ):
- return self.list[0:i+1]
- elif current_pos < n:
- a1 = i
- elif current_pos > n:
- a2 = i
- #a sample function that works correctly with this decorator
- @growing_limited_by_arg_mem_list
- def simple_primes_generator (num, primes = [2,3]):
- if num == 2:
- return [2]
- i = primes[-1] + 2
- while i <= num:
- is_prime = True
- for prime in primes:
- if i % prime == 0:
- is_prime = False
- break
- if is_prime:
- primes += [i]
- i+=2
- return primes
Andreu Correa Casablanca commented the snippet Memorizer Decorator for accumulative lists 2 years, 8 months ago · View
Probably, the part of the code that selects the variable a1 and a2 should be deleted and keep only the binary search to improve the code.