-
I did almost the exact same thing but with Pandas dataframes instead, now I've changed it to lists it runs in barely a second. If you only have a hammer...
I also looked into breaking from nested loops but it wasn't trivial so I decided not to bother. But reading again the highest voted answer to this question has a solution.
import pandas as pd from datetime import datetime starttime = datetime.now() print(starttime) input_df = pd.read_csv("day1_input.csv", header=None) \#part1 for index1, row in input_df.iterrows(): for index2, row in input_df.iterrows(): if row[0] + input_df[0][index1] == 2020 : print(row[0] * input_df[0][index1]) finishtime = datetime.now() print(finishtime) \#part2 for index1, row in input_df.iterrows(): for index2, row in input_df.iterrows(): for index3, row in input_df.iterrows(): if row[0] + input_df[0][index1] + input_df[0][index2] == 2020 : print(row[0] * input_df[0][index1]* input_df[0][index2]) finishtime = datetime.now() print(finishtime)
-
Granted it's not absolutely necessary for day 1 but if you don't see the obvious optimisation then some of the later puzzles are going to be tough going.
Hint: You don't need a nested for loop for part 1 if you use the right data structure. You only need a single nested for loop (e.g. two for loops, not three) for part 2.
https://github.com/ips-james/AdventOfCode/blob/main/day1.py
Anyone know how I make it stop searching after it's found one of the combinations?