beapythondev

Narcissistic number with multi-processing and memoization

Oct 9th, 2022 (edited)
1,717
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.42 KB | None | 0 0
  1. # Video Channel: youtube.com/beapythondev
  2. # My Blog : https://beapython.dev
  3.  
  4. import time
  5. from multiprocessing import Pool, cpu_count
  6.  
  7. def is_narc(s,e, memo_table):
  8.     to_return = []
  9.     for i in range(s,e):
  10.         # Mike also pointed we save cycles by storing the length as a variable
  11.         str_i = str(i)
  12.         len_i = len(str_i)
  13.         if (i == sum(memo_table[len_i-1][int(d)] for d in str_i)):
  14.             to_return.append(i)
  15.     return to_return
  16.  
  17. if __name__ == '__main__':
  18.     t_start = time.time()
  19.    
  20.     # Credit to Mike Kerry for idea to memoize the calculation of the powers before hand
  21.     #
  22.     # @Stefan for modifying code to pass this to the processes so it only needs to calculate
  23.     # once
  24.     memo_table = [[i ** j for i in range(10)] for j in range(1,10)]
  25.  
  26.     l = 10 # Left start index
  27.     ws = 25000 # Window size
  28.     results = []
  29.    
  30.     # Initialize p_size equal to max threads on your hardware
  31.     p_size = cpu_count()
  32.  
  33.     with Pool(p_size) as p:
  34.         while len(results) < 15:
  35.             # launching multiple evaluations asynchronously *may* use more processes
  36.             multiple_results = [p.apply_async(is_narc, (l + (ws * i), l+(ws*(i+1)), memo_table)) for i in range(p_size)]
  37.             [results.extend(r) for r in [res.get(timeout=1) for res in multiple_results]]
  38.             l += (ws * p_size)
  39.  
  40.     print(results)
  41.     print(f"Processing time = {time.time() - t_start}")
  42.  
Advertisement
Add Comment
Please, Sign In to add comment