r/adventofcode • u/daggerdragon • Dec 02 '20
SOLUTION MEGATHREAD -🎄- 2020 Day 02 Solutions -🎄-
--- Day 2: Password Philosophy ---
Advent of Code 2020: Gettin' Crafty With It
- T-4 days until unlock!
- Full details and rules are in the Submissions Megathread
Post your solution in this megathread. Include what language(s) your solution uses! If you need a refresher, the full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.
Reminder: Top-level posts in Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.
This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.
EDIT: Global leaderboard gold cap reached at 00:02:31, megathread unlocked!
102
Upvotes
View all comments
2
u/code_may_explode Dec 02 '20 edited Dec 02 '20
Solution in Python- uses class to handle data- spread out some of the bool statements for readability- instead of striping the string when loading it in and taking one off the index when retrieving a char one could skip both steps, yet that would cause all strings to be saved into the class attribute with a trailing space.
Feel free to feedback :)
class Password(object):"""Class for modeling the input data."""character : str = ''lower_limit : int = 0upper_limit : int = 0string : str = ''def __init__(self, inputString):input_data = inputString.split(':')policy = input_data[0]policy_data = policy.split(' ')policy_limit = policy_data[0].split('-')self.character = policy_data[1]self.lower_limit = int(policy_limit[0])self.upper_limit = int(policy_limit[1])self.string = input_data[1].strip()def is_old_valid(self)->bool:char_count = len(self.string.split(self.character))-1return self.lower_limit <= char_count <= self.upper_limitdef is_new_valid(self)->bool:is_first_char = self.is_char_at(self.character, self.lower_limit)is_second_char = self.is_char_at(self.character, self.upper_limit)return is_first_char != is_second_chardef is_char_at(self, char, index)->bool:try:return (self.string[index-1] == char)except IndexError as e:return False"""Opening and processing data.""""with open('input.txt') as fh:passwords = [Password(constString) for constString in fh.readlines()]old_valid_passwords : int = 0new_valid_passwords : int = 0for password in passwords:if password.is_old_valid():old_valid_passwords += 1if password.is_new_valid():new_valid_passwords += 1print(f'{old_valid_passwords=}', f'{new_valid_passwords=}')