DEV Community


Discussion on: Advent of code: 2020 Day 01

shalvah profile image
Shalvah • Edited

Nice! Some extra optimisations:

  • Don't read the whole file at once, as it could be very large. Use some sort of stream and read line by line. That way, you might even get the answer without reading the whole file. Don't know about Python; in JS, I used the readline module.
  • Don't do the casting to integers and trimming upfront. You can do that as you encounter each entry.

These won't improve the time complexity, but they'll definitely save some time.

I like your solutions. My solution to Part 2 was probably faster but uglier—an outer loop where I added the current number to a set of the numbers we'd seen and an inner loop where I looped over all the numbers we'd seen and checked if the remaining number to get 2020 was also there. But I prefer your approach of computing the sum and product.

I think, in your solution, you could probably combine the second iteration with the first double iteration, since you're iterating over the same set of numbers. Possibly something like:

def part2(entries):
    rests = {}
    for x in entries:
        for y in entries:
            rests[x + y] = x * y
        rest = 2020 - x
        if rest in rests:
            return x * rests[rest]
Enter fullscreen mode Exit fullscreen mode