⛄ Day 2

Advent of Code is a coding challenge that releases a puzzle every day starting December 1st up until the 25th - like an Advent Calendar but no stale chocolate...

Part 1

Given a list following the format: '<min>-<max> <char>: <password>' find all passwords where char is present at least min times and at most max times
Solution:
                                
                                    
    import csv
    

    def parse_input(file_name):
    with open(file_name, 'r') as data:
        return [line[0].split(': ') for line in data]
    
    
    def get_policy(string):
        s = string.split(' ')
        mn = s[0].split('-')
        m = mn[0]
        n = mn[1]
        char = s[1]
    
        return int(m), int(n), char
    

    def letter_histo(word):
        h = {}
        word.replace(' ', '')
        char_arr = list(word)
        for char in char_arr:
            h[char] = h.get(char, 0) + 1
    
        return h
    

    def get_count_valid_passwords(password_list):
        count = 0
    
        for i in password_list:
            policy_data = i[0]
            password = i[1]
    
            min, max, char = get_policy(policy_data)
            histo = letter_histo(password)
    
            frq = histo.get(char)
            if frq is not None:
                if frq >= min and frq <= max:
                    count += 1
    
        return count
    
    
    print(get_count_valid_passwords(parse_input('day2.txt')))
        
                                
                            

Part 2

Given a list following the format '<idx_1>-<idx_2> <char>: <password>' find all passwords where char is present at either idx_1 or idx_2 in password
Solution:
                                
                                    
    def valid_word(i, j, char, word):
        char_arr = list(word)
        char_i = char_arr[i-1]
        char_j = char_arr[j-1]
        if char_i == char and char_j == char:
            return False
        elif char_i != char and char_j != char:
            return False
        else:
            return True
    
    
    def get_count_valid_passwords_2(password_list):
        count = 0
    
        for i in password_list:
            policy_data = i[0]
            password = i[1]
    
            idx_1, idx_2, char = get_policy(policy_data)
            is_valid = valid_word(idx_1, idx_2, char, word)
    
            if is_valid:
                count += 1
    
        return count
    
    
    print(get_count_valid_passwords_2(parse_input('day2.txt')))