day02_part2_v2.py (1422B)
1 #!/usr/bin/env python 2 """I have a bit of downtime so I'm trying out another implementation of Part 2, 3 all in 'base' Python""" 4 5 import timeit 6 from utils import get_puzzle_input 7 import day02_part2 8 9 def solve_puzzle(input_string): 10 commands = ((c, float(d)) for c, d in \ 11 (x.split(' ') for x in input_string.split('\n') if len(x) > 0)) 12 13 horizontal_position = 0 14 depth = 0 15 aim = 0 16 17 for c, d in commands: 18 if c == 'down': 19 aim += d 20 elif c == 'up': 21 aim -= d 22 else: # c == 'forward' 23 horizontal_position += d 24 depth += aim * d 25 26 return depth * horizontal_position 27 28 if __name__ == "__main__": 29 input_string = get_puzzle_input(2) 30 31 # Check that the results are the same 32 assert solve_puzzle(input_string) == day02_part2.solve_puzzle(input_string) 33 34 # Compare the timings 35 loops = 1000 36 time_old = timeit.timeit(lambda: day02_part2.solve_puzzle(input_string), 37 number=loops) 38 time_new = timeit.timeit(lambda: solve_puzzle(input_string), 39 number = loops) 40 print(f"Pandas implementation: {time_old:.4f} s for {loops} loops", 41 f"Generator implementation: {time_new:.4f} s for {loops} loops", 42 sep='\n') 43 # Results on my laptop 44 #> Pandas implementation: 5.3778 s for 1000 loops 45 #> Generator implementation: 0.3710 s for 1000 loops