import re from IPython import embed data = [str.strip(x) for x in open("input")] pattern = r"(\d+)-(\d+) ([a-z]): ([a-z]+)" prog = re.compile(pattern) # Part 1 valid_count = 0 for x in data: low, high, char, password = prog.match(x).groups() if int(low) <= password.count(char) <= int(high): valid_count += 1 print(valid_count) # Part 2 valid_count = 0 for x in data: low, high, char, password = prog.match(x).groups() if [password[int(low) - 1], password[int(high) - 1]].count(char) == 1: valid_count += 1 print(valid_count)