Advent of Code 2018 – Day 1

In an effort to learn python I am working my way through the Advent of Code challenges.  Advent of Code is a coding challenge done during the holiday season every year, its a fun way to keep your skills sharp.  It is also a great way to try and learn a new language because it gives you some focused challenges to figure out how the new language works to solve the problem. Check it out here https://adventofcode.com/2018

My full solution is on github here https://github.com/JustLogic/AdventOfCode2018_Python/tree/master/Day1

Part 1 Solution

import os

#Get File Path
script_dir = os.path.dirname(__file__)
rel_path = "Day1_Input.txt"
abs_file_path = os.path.join(script_dir, rel_path)

def is_int(value):
  try:
    int(value)
    return True
  except:
    print(value)
    return False

def do_frequency_calibration():
    finalFrequency = 0

    with open(abs_file_path) as fp:  
        for cnt, frequency in enumerate(fp):
            if is_int(frequency):
                finalFrequency += int(frequency)
    
    print(finalFrequency)
    return

do_frequency_calibration()

Part 2 Solution

import os

#Get File Path
script_dir = os.path.dirname(__file__)
rel_path = "Day1_Input.txt"
abs_file_path = os.path.join(script_dir, rel_path)

def is_int(value):
  try:
    int(value)
    return True
  except:
    print(value)
    return False

def main():
    intialFrequency = 0
    calculatedFrequencies = []
    calculatedFrequencies.append(intialFrequency)

    with open(abs_file_path) as f:  
      inputData = f.readlines()
    
    inputData = [x.strip() for x in inputData] 
    inputFrequenciesChanges = inputData

    do_calc(inputFrequenciesChanges, intialFrequency, calculatedFrequencies)



def do_calc(frequencyChanges, currentFrequency, calculatedFrequencies):
    iFoundTheSecondFrequency = False

    for frequency in frequencyChanges:
      if is_int(frequency):
        currentFrequency += int(frequency)
        if currentFrequency in calculatedFrequencies:
            iFoundTheSecondFrequency = True
            print("Found second frequency: ", currentFrequency)
            break
        else:
            calculatedFrequencies.append(currentFrequency)                
    
    if iFoundTheSecondFrequency == False:
        print("checking list again")
        print("Current Frequency: ", currentFrequency)
        print("Num items in CalculatedFrequencies: ", len(calculatedFrequencies))
        do_calc(frequencyChanges, currentFrequency, calculatedFrequencies)
    else:
        return

main()