Advent of Code – Day 1

For the past few years, Eric Wastl has been posting a series of small programming puzzles during the days of advent. The puzzles are in two parts, which are often related, and are at a variety of skill levels.  I’m going to aim to do these puzzles each day and blog about my progress.  I’ll also be posting my notebook to GitHub here.

The puzzle – part 1:

Find the sum of all digits that match the next digit in the list.  The list is circular, so the digit after the last digit is the first in the list.

def circ_sum(target):
    total = 0
    target = map(int, str(target))
    for i in range(0,len(target)-1):
        if target[i]==target[i+1]:
            total +=target[i]
    if target[len(target)-1]==target[0]:
    return total

So I made a function with a name that wasn’t great – circ_sum (circular sum) – need to work on my naming.  I wanted to use a list comprehension strategy and so needed to convert the integer to a list – I used a map to do that.

I then looped through the list and did the comparision – if they matched they got added to the total and I dealt with the last terms separately.

I initially used two for loops but realized my error.

Part 2:

Now, instead of considering the next digit, it wants you to consider the digit halfway around the circular list.  The list will always have an even number of terms.

def circ_sum_step(target):
    total = 0
    target = map(int, str(target))
    step = len(target)/2
    for i in range(len(target)-1):
        if (i + step) < len(target):
            if target[i]==target[i+step]:
                total +=target[i]
            if target[i]==target[i-step]:
                total +=target[i]
    if target[len(target)-1]==target[step-1]:
    return total

I copied my original function and scoped a variable step based on half the length of the list.  This time, I needed to check whether the sum of the step and index term were greater than the length of the list.

I made an error in the else clause initially in which I had target[step-i] in the comparison.  Took me a few minutes to notice it but once I did it all went well.


I didn’t find this too challenging.  There are probably better ways to do this and I’ll have a look but my method worked and got the result I wanted.  I got my two stars and I’m looking forward to tomorrow’s puzzle.


Leave a Reply