aoc/02/02.py

37 lines
986 B
Python
Raw Normal View History

2020-12-02 15:46:36 +00:00
def read_file():
with open("input.txt","r") as f:
return f.read().split('\n')
def part1(passwords):
valid = 0
for entry in passwords:
[policy, password] = entry.split(': ')
[counts, character] = policy.split(' ')
[minimum, maximum] = counts.split('-')
2020-12-02 15:48:56 +00:00
minimum = int(minimum)
maximum = int(maximum)
if minimum <= password.count(character) <= maximum:
2020-12-02 15:46:36 +00:00
valid += 1
return valid
def part2(passwords):
valid = 0
for entry in passwords:
[policy, password] = entry.split(': ')
[positions, character] = policy.split(' ')
[p1, p2] = positions.split('-')
p1 = int(p1) - 1 # convert 1-index to 0-index
p2 = int(p2) - 1 # convert 1-index to 0-index
first_match = password[p1] == character
second_match = password[p2] == character
if first_match + second_match == 1: # exclusive or
valid += 1
return valid
def main():
passwords = read_file()
print(f"Part 1: {part1(passwords)}")
print(f"Part 2: {part2(passwords)}")
if __name__ == "__main__":
main()