Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Video Channel: youtube.com/beapythondev
- # My Blog : https://beapython.dev
- import time
- from multiprocessing import Pool, cpu_count
- def is_narc(s,e, memo_table):
- to_return = []
- for i in range(s,e):
- # Mike also pointed we save cycles by storing the length as a variable
- str_i = str(i)
- len_i = len(str_i)
- if (i == sum(memo_table[len_i-1][int(d)] for d in str_i)):
- to_return.append(i)
- return to_return
- if __name__ == '__main__':
- t_start = time.time()
- # Credit to Mike Kerry for idea to memoize the calculation of the powers before hand
- #
- # @Stefan for modifying code to pass this to the processes so it only needs to calculate
- # once
- memo_table = [[i ** j for i in range(10)] for j in range(1,10)]
- l = 10 # Left start index
- ws = 25000 # Window size
- results = []
- # Initialize p_size equal to max threads on your hardware
- p_size = cpu_count()
- with Pool(p_size) as p:
- while len(results) < 15:
- # launching multiple evaluations asynchronously *may* use more processes
- multiple_results = [p.apply_async(is_narc, (l + (ws * i), l+(ws*(i+1)), memo_table)) for i in range(p_size)]
- [results.extend(r) for r in [res.get(timeout=1) for res in multiple_results]]
- l += (ws * p_size)
- print(results)
- print(f"Processing time = {time.time() - t_start}")
Advertisement
Add Comment
Please, Sign In to add comment