def preamble_generator(dataset): preamble_length = len(dataset) for i in range(0, preamble_length): for j in range(i + 1, preamble_length): yield dataset[i] + dataset[j] def is_contained_in(preamble_dataset, value): for x in preamble_generator(preamble_dataset): if value == x: return True return False def get_first_noncompliant_no(dataset, preamble_length): for i in range(preamble_length, len(dataset)): preamble = dataset[i - preamble_length:i] value = dataset[i] if not is_contained_in(preamble, value): return value assert False, "Wtf?" def get_range(nc, dataset): l = len(dataset) for i in range(0, l): for j in range(i, l): ds = dataset[i:j] s = sum(ds) if s > nc: break if nc == s: return ds assert False, "Wtf?" def process(filename, preamble_length): with open(filename, "r", encoding="utf-8") as f: nums = [int(x) for x in f] nc = get_first_noncompliant_no(nums, preamble_length) print(f"1: First non-compliant no. in {filename} is {nc}.") r = get_range(nc, nums) a = min(r) + max(r) print(f"2: Answer is {a}.") process("test.txt", 5) print("-"*80) process("data.txt", 25)