re: AoC Day 1: Chronal Calibration VIEW POST


So excited about this 🙌🏻!


Part 1

data = open('input.txt', 'r')
total = 0
for line in data:
    total += int(line)

Part 2

data = [int(i) for i in open('input.txt', 'r')]

def get_first_duplicate_total(data):
    total = 0
    prev_totals = set([0])
    while True:
        for i in data:
            total += i
            if total in prev_totals:
                return total
    return total


I also learned about itertools.cycle through reading the Reddit solutions, that would make it so that I don't need the while True:


I'd also suggest to use a context manager (the with keyword) for clean opening and closing of files.

Part 1:

with open("input.txt") as f:
    freq = sum(int(i.strip()) for i in f)

Part 2:

from itertools import cycle

with open("input.txt") as f:
    freqs = [int(i.strip()) for i in f]

seen = set()
current = 0
for f in cycle(freqs):
    if current in seen:
        current += f

Also: "Hey checkout my Github Repo!"


True! Always forget to do that since I really only do file handling for code challenges at this point.


Ah! So good. The clean-ness of Python never stops making me happy!

Using a set was a good idea. I didn't think of that, but it would be a lot faster for checking whether or not an item was present.

I'm going to offer unsolicited suggestions, but feel free to totally ignore them if you already knew about them (probable) or don't like them, since your solution already looks really nice.

  1. For part one, generator expressions could be your friend:
data = open('input.txt', 'r')
total = sum(int(line) for line in data)
  1. For the second part, check out itertools.cycle.

Awesome! Yes, thank you! Found out about itertools.cycle this morning -- feels super niche but still really cool.

Part one could also be a one-liner!

print(sum(int(line for line in open('input.txt', 'r'))))
code of conduct - report abuse