illuminati229

AoC 2023 Day 09

Dec 9th, 2023
1,005
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.56 KB | None | 0 0
  1. from time import time
  2.  
  3.  
  4. def timer_func(func):
  5.     # This function shows the execution time of
  6.     # the function object passed
  7.     def wrap_func(*args, **kwargs):
  8.         t1 = time()
  9.         result = func(*args, **kwargs)
  10.         t2 = time()
  11.         print(f'Function {func.__name__!r} executed in {(t2 - t1):.4f}s')
  12.         return result
  13.  
  14.     return wrap_func
  15.  
  16.  
  17. def difference(a: list):
  18.     if len(a) == 1:
  19.         return []
  20.     b = []
  21.     for i, x in enumerate(a[:-1]):
  22.         b.append(a[i+1] - x)
  23.     return b
  24.  
  25.  
  26. def is_constant(a):
  27.     c = a[0]
  28.     for x in a[1:]:
  29.         if x != c:
  30.             return False
  31.     return True
  32.  
  33.  
  34. def next_value(a):
  35.     d = difference(a)
  36.     if is_constant(d):
  37.         return a[-1] + d[0]
  38.     else:
  39.         return a[-1] + next_value(d)
  40.  
  41.  
  42. def prior_value(a):
  43.     d = difference(a)
  44.     if is_constant(d):
  45.         return a[0] - d[0]
  46.     else:
  47.         return a[0] - prior_value(d)
  48.  
  49.  
  50. @timer_func
  51. def day09(filepath, part2=False):
  52.     with open(filepath) as fin:
  53.         lines = [line.strip() for line in fin.readlines()]
  54.  
  55.     hist_sum = 0
  56.     if not part2:
  57.         for line in lines:
  58.             hist_sum += next_value([int(x) for x in line.split()])
  59.     else:
  60.         for line in lines:
  61.             hist_sum += prior_value([int(x) for x in line.split()])
  62.  
  63.     return hist_sum
  64.  
  65.  
  66. def main():
  67.     assert day09('test09') == 114
  68.     print(f"Part 1: {day09('input09')}")
  69.  
  70.     assert day09('test09', True) == 2
  71.     print(f"Part 2: {day09('input09', True)}")
  72.  
  73.  
  74. if __name__ == '__main__':
  75.     main()
  76.  
Advertisement
Add Comment
Please, Sign In to add comment