r/adventofcode • • Dec 02 '20

SOLUTION MEGATHREAD -🎄- 2020 Day 02 Solutions -🎄-

--- Day 2: Password Philosophy ---


Advent of Code 2020: Gettin' Crafty With It


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

1.2k comments sorted by

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 = 0
upper_limit : int = 0
string : 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))-1
return self.lower_limit <= char_count <= self.upper_limit

def 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_char

def 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 = 0
new_valid_passwords : int = 0
for password in passwords:
if password.is_old_valid():
old_valid_passwords += 1
if password.is_new_valid():
new_valid_passwords += 1

print(f'{old_valid_passwords=}', f'{new_valid_passwords=}')

1

u/daggerdragon Dec 02 '20

Use code block formatting (four spaces in front of every line) in Markdown mode instead of marking every line as an inline code block.

1

u/fiddle_n Dec 02 '20

There's no need to subclass from object in Python 3, FYI. That's only needed in Python 2.