advent-of-code/solutions/2/python/main.py

28 lines
854 B
Python
Raw Normal View History

2020-12-02 12:07:57 +00:00
from os.path import join, dirname
def checkRow(row: str, alternative=False) -> bool:
rule, password = map(lambda s: s.strip(), row.split(':'))
amount, char = rule.split(' ')
minimum, maximum = map(int, amount.split('-'))
if alternative:
2020-12-02 12:14:40 +00:00
return (password[minimum - 1] == char) ^ (password[maximum - 1] == char)
2020-12-02 12:07:57 +00:00
else:
occurrences = password.count(char)
return minimum <= occurrences <= maximum
2020-12-04 18:45:03 +00:00
data = join(dirname(__file__), '../data.txt')
2020-12-02 12:07:57 +00:00
with open(data) as f:
valid = 0
valid_alt = 0
rows = list(f.read().strip().split('\n'))
for row in rows:
if(checkRow(row)):
valid += 1
if(checkRow(row, alternative=True)):
valid_alt += 1
print(f'Found {valid} valid passwords.')
print('Policy changed...')
print(f'Found {valid_alt} valid passwords.')