54 lines
1.3 KiB
Python
54 lines
1.3 KiB
Python
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())
|