Advent of Code Day 1

This was a fun one! Took me around 40 minutes, but most of that time was getting more familiar with Python. One thing I learned is that if you want to access the index of an array you're looping, you need to use enumerate(). It was also cool getting to play with Python's built-in file reading/editing. Coming from Javascript, this is a much simpler way to do things than Javascript's file system.

What do you think of my solution? What could I have done better?

import csv

list1 = []
list2 = []
totalDifference = 0
similarityScore = 0
frequencyMap = {}
frequencyScore=0

def getLists():

    # Format text to replace spaces with a \tab so it can be read into array
    with (open('data.csv', 'r') as data,
        open('newdata.csv', 'w') as new_data):
        for line in data:
            new_data.write(line.replace('   ', '\t'))

    with open('newdata.csv') as new_data:
        reader=csv.reader(new_data, delimiter='\t')
        for line in reader:
            list1.append(int(line[0]))
            list2.append(int(line[1]))

        list1.sort()
        list2.sort()

getLists()

for i, item in enumerate(list1):
    if(item not in frequencyMap):
        frequencyMap[item] = 0
    totalDifference += (abs(item - (list2[i])))

for i, item in enumerate(list2):
    if(item in frequencyMap):
         frequencyMap[item] += 1

for key, value in frequencyMap.items():
  frequencyScore += (key * value)

print(totalDifference)
print(frequencyScore)        

要查看或添加评论,请登录

Brodie Heginbotham的更多文章

  • Day 2: Advent of Code

    Day 2: Advent of Code

    This one was much harder, in my opinion. But that's partly because I added some challenges to myself.

社区洞察

其他会员也浏览了