Implement 2019 day 4

This commit is contained in:
2021-01-23 17:52:59 +01:00
parent 7a292b026d
commit ad3029759a
2 changed files with 55 additions and 0 deletions

38
2019/aoc2019/day04.py Normal file
View File

@@ -0,0 +1,38 @@
import itertools
from typing import TextIO
def read_range(data: TextIO) -> range:
a, b = next(data).split('-')
return range(int(a), int(b) + 1) # plus one because inclusive
def valid(number: int, strict: bool) -> bool:
s = str(number)
prev = '/' # is smaller than '0'
has_group = False
if len(s) != 6:
return False
for k, g in itertools.groupby(s):
if k < prev:
return False
prev = k
amount = sum(1 for _ in g)
if amount == 2 or not strict and amount > 2:
has_group = True
return has_group
def part1(data: TextIO) -> int:
return sum(1 for password in read_range(data) if valid(password, False))
def part2(data: TextIO) -> int:
return sum(1 for password in read_range(data) if valid(password, True))

17
2019/tests/test_day04.py Normal file
View File

@@ -0,0 +1,17 @@
import pytest
from aoc2019.day04 import valid
@pytest.mark.parametrize('number,strict,expected', [
(122345, False, True),
(111123, False, True),
(111111, False, True),
(223450, False, False),
(123789, False, False),
(112233, True, True),
(123444, True, False),
(111122, True, True)
])
def test_valid(number: int, strict: bool, expected: bool) -> None:
assert valid(number, strict) == expected