Guest User

Untitled

a guest
Dec 7th, 2024
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.90 KB | None | 0 0
  1. from multiprocessing import Pool
  2. import timeit
  3. import multiprocessing
  4. import math
  5.  
  6. def row_generator(filename):
  7.     # Row generator rather than returning entire file. didn't actually save much time though
  8.     with open(filename, 'r') as f:
  9.         for line in f:
  10.             yield line.strip()
  11.  
  12. def check_row(row):
  13.     target, calibration_data = row.split(":")
  14.     target = int(target)
  15.     calibration_data = [int(x) for x in calibration_data.strip().split(" ")]
  16.     l = [calibration_data[0]]
  17.     for i in calibration_data[1:]:
  18.         temp_list = []
  19.         for j in l:
  20.             temp_list.append(j+i)
  21.             temp_list.append(i*j)
  22.             digits = int(math.log10(i)) + 1 #math is faster than len(str(i))
  23.             concat_val = j * (10 ** digits) + i #math is much faster than int(str(j)+str(i))
  24.             temp_list.append(concat_val)
  25.         l = temp_list
  26.     if target in l:
  27.         return target
  28.     else:
  29.         return 0
  30.  
  31. def main():
  32.     with Pool(processes=12) as p:
  33.         #imap over map to make use of generator and get started calculating faster
  34.         results = p.imap(check_row, row_generator('input.txt'))
  35.         total = sum(results)
  36.     print(total)
  37.  
  38. if __name__ == "__main__":
  39.     print(multiprocessing.cpu_count())
  40.     duration = timeit.timeit("main()", globals=globals(), number=1)
  41.     print("Duration:", duration)
  42.  
  43. """
  44.    Test 1: baseline speed on first solve
  45.    Time: 6.6303s
  46.  
  47.    Test 2: Stopped using temp_list.copy() and just reassigned l to temp_list. No need to copy
  48.    Time: 6.4635s
  49.        
  50.    Test 3: Removed all print statements
  51.    Time: 6.3357s
  52.  
  53.    Test 4: Set up multiprocessing with Pool().map()
  54.    Time: 1.8076s
  55.  
  56.    Test 5: Changed from string concatenation to math for concatenating numbers
  57.    Time: 1.3771s
  58.  
  59.    Test 6: Changed Pool().map to Pool().imap and changed file loading to file streaming
  60.    Time: 1.2846s
  61.    """
Advertisement
Add Comment
Please, Sign In to add comment