import re re_pw = re.compile(r"^(?P\d+)-(?P\d+)\s+(?P\S): (?P.+)$") num_valid = 0 num_valid_2 = 0 with open("data.txt", "r", encoding="utf-8") as f: for l in f: m = re_pw.match(l) assert m, "wtf?" min_letters = int(m.group("min")) max_letters = int(m.group("max")) pw = m.group("password") key = m.group("key") is_valid = min_letters <= pw.count(key) <= max_letters if is_valid: num_valid += 1 is_valid_2 = bool(pw[min_letters-1] == key) != bool(pw[max_letters-1] == key) if is_valid_2: num_valid_2 += 1 print(f"{l.rstrip()}\t{is_valid}\t{is_valid_2}") print(f"\nNum valid pwds (1): {num_valid}") print(f"\nNum valid pwds (2): {num_valid_2}")