Skip to content

Commit 7faf80d

Browse files
committed
day02 done
1 parent a39c618 commit 7faf80d

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

day02/day02.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#!/usr/bin/env python3
2+
3+
import re
4+
5+
def check_policy(policy: str, password: str, mode: int = 1) -> bool:
6+
numbers, char = policy.split(" ")
7+
lower_bound, upper_bound = [int(num) for num in numbers.split("-")]
8+
9+
if mode == 1:
10+
occ = password.count(char)
11+
return lower_bound <= occ <= upper_bound
12+
else:
13+
# policy starts at place 1, not 0 in the string
14+
matches = [match.start()+1 for match in re.finditer(char, password)]
15+
return bool((lower_bound in matches) ^ (upper_bound in matches))
16+
17+
18+
19+
20+
if __name__ == "__main__":
21+
with open("input", "r") as infile:
22+
check_lines = [line.strip().split(":") for line in infile]
23+
print("Valid passwords for part1:", sum([check_policy(policy.strip(), password.strip()) for policy, password in check_lines]))
24+
print("Valid passwords for part2:", sum([check_policy(policy.strip(), password.strip(), 2) for policy, password in check_lines]))

0 commit comments

Comments
 (0)