Login Password

Snippets - Detail

Memorizer Decorator for accumulative lists

Avatar Image
This decorator allows to optimize the calculus of some lists (with growing values, such as primes list) using previous executions.
Language: Python
  1. #our magic decorator
  2. class growing_limited_by_arg_mem_list:
  3.         def __init__ (self, function):
  4.                 self.max   = -1
  5.                 self.list  = []
  6.                 self.function = function
  7.        
  8.         def __call__ (self, *args):
  9.                 n = args[0]
  10.                
  11.                 if n > self.max:
  12.                         if self.max > 0:
  13.                                 self.list = self.function (n, self.list)
  14.                         else:
  15.                                 self.list = self.function (n)
  16.                         self.max = n
  17.                         return self.list
  18.                 else:
  19.                         a1 = 0
  20.                         a2 = len(self.list)
  21.                        
  22.                         i = 0
  23.                         while True:
  24.                                 i = (a2+a1)/2
  25.                                 current_pos = self.list[i]
  26.                                 if current_pos == n or ( current_pos < n and self.list[i+1] > n ):
  27.                                         return self.list[0:i+1]
  28.                                 elif current_pos < n:
  29.                                         a1 = i
  30.                                 elif current_pos > n:
  31.                                         a2 = i
  32.  
  33. #a sample function that works correctly with this decorator
  34. @growing_limited_by_arg_mem_list
  35. def simple_primes_generator (num, primes = [2,3]):
  36.         if num == 2:
  37.                 return [2]
  38.  
  39.         i = primes[-1] + 2
  40.         while i <= num:
  41.                 is_prime = True
  42.                 for prime in primes:
  43.                         if i % prime == 0:
  44.                                 is_prime = False
  45.                                 break
  46.                 if is_prime:
  47.                         primes += [i]
  48.                
  49.                 i+=2
  50.         return primes
bettercodes.org is released as free software without warranties under GNU Affero GPL v3