import math INPUT_FILE = "input.txt" # Read File with open(INPUT_FILE, 'r') as file: groups: list[str] = file.read().strip().split(',') # Parse Ranges ranges: list[tuple[int, int]] = [ (int(n1), int(n2)) for n1, n2 in [group.split('-') for group in groups] ] # Check for invalid ids invalid_ids: set[int] = set() for (n1, n2) in ranges: for n in range(n1, n2 + 1): str_n: str = str(n) n_len: int = len(str_n) mid: int = math.ceil(n_len / 2) for pattern_length in range(1, mid + 1): # If number cannot be split by pattern length it cannot be repeated at least twice if n_len % pattern_length != 0: continue pattern = str_n[:pattern_length] all_match = True repeats = 0 for i in range(0, n_len, pattern_length): if str_n[i:i + pattern_length] != pattern: all_match = False break else: repeats += 1 if all_match and n not in invalid_ids and repeats >= 2: invalid_ids.add(n) print(f'Invalid Id: {n}') print(f'Sum of Invalid Ids: {sum(invalid_ids)}')