DEV Community

Viper
Viper

Posted on • Edited on

Advent of Code 2020: Python Solution Day 9

This challenge is the easiest one I encountered on this season. And I was able to find a working algorithm. Still I am not even on top 7k. I started with copying test example and pasting on day9_test.txt and my input on day9.txt both are at same directory as my notebook is.

Lets share your solution too.

Challenge 1

with open("day9.txt", "r") as fp:
    lines = [int(line.rstrip()) for line in fp.readlines()]
# lines

def challenge1(codes, premable):
    previous_stack = []
    i = 0
    start = 0
    end = start+premable
    curr_index = premable
    while curr_index < len(codes)-1:
        stack = codes[start:end]
        if curr_index > len(stack)-1:
            start+=1
            end+=1
            valid = False
            for i in stack[:-1]:
                for j in stack[1:]:
                    #print(codes[curr_index], i, j)
                    if i+j == codes[curr_index]:
                        valid = True
                        break
                    else:
                        valid == False
                if valid:
                    break
            if valid == False:
                return codes[curr_index]

        curr_index+=1
#         print(stack)
#         break

challenge1(lines, 25)
Enter fullscreen mode Exit fullscreen mode

Challenge 2

Used NumPy for taking sum faster.

import numpy as np
def challenge2(codes, invalid_num):
    contigous_list = []

    for i in range(0, len(codes)-1):
        for j in range(1, len(codes)-1):
            stack = np.array(codes[i:j])
            if np.sum(stack) == invalid_num:
                print(stack, stack.min()+stack.max())
#             print(stack)
challenge2(lines, challenge1(lines, 25))
Enter fullscreen mode Exit fullscreen mode

I write blogs about Computer Vision projects on my GitHub page q-viper.github.io and if you got some time please share yours too.

Top comments (1)

Collapse
 
qviper profile image
Viper

It is so neat an clear. Thank you for sharing.