Is this acmeism?
This commit is contained in:
53
aoc2020/py/day02/solution.py
Normal file
53
aoc2020/py/day02/solution.py
Normal file
@@ -0,0 +1,53 @@
|
||||
import sys
|
||||
|
||||
|
||||
def main() -> int:
|
||||
n_valid = 0
|
||||
total = 0
|
||||
|
||||
for pol_pas in [PolicyPassword.fromstring(s) for s in sys.stdin.readlines(False)]:
|
||||
if pol_pas.is_valid():
|
||||
n_valid += 1
|
||||
total += 1
|
||||
|
||||
print(f"{n_valid}/{total} valid")
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
class Policy:
|
||||
def __init__(self, char: str, pos1: int, pos2: int):
|
||||
self.char = char
|
||||
self.pos1 = pos1
|
||||
self.pos2 = pos2
|
||||
|
||||
@classmethod
|
||||
def fromstring(cls, input_string) -> "Policy":
|
||||
parts = [s.strip() for s in input_string.split(" ")][:2]
|
||||
pos = [int(s) for s in parts[0].split("-")][:2]
|
||||
return cls(parts[1], pos[0], pos[1])
|
||||
|
||||
def is_valid(self, password: str) -> bool:
|
||||
matches = 0
|
||||
for pos in (self.pos1 - 1, self.pos2 - 1):
|
||||
if password[pos] == self.char:
|
||||
matches += 1
|
||||
return matches == 1
|
||||
|
||||
|
||||
class PolicyPassword:
|
||||
def __init__(self, policy: "Policy", password: str):
|
||||
self.policy = policy
|
||||
self.password = password
|
||||
|
||||
@classmethod
|
||||
def fromstring(cls, input_string: str) -> "PolicyPassword":
|
||||
parts = [s.strip() for s in input_string.split(":")][:2]
|
||||
return cls(Policy.fromstring(parts[0]), parts[1])
|
||||
|
||||
def is_valid(self) -> bool:
|
||||
return self.policy.is_valid(self.password)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
Reference in New Issue
Block a user