import logging from itertools import pairwise from sys import stdout logger = logging.Logger(__name__) formatter = logging.Formatter('[%(asctime)s][%(levelname)s] %(message)s') sh = logging.StreamHandler(stdout) sh.setLevel(logging.INFO) sh.setFormatter(formatter) fh = logging.FileHandler("./day02-1.log", mode="w", encoding="utf-8") fh.setLevel(logging.DEBUG) fh.setFormatter(formatter) logger.addHandler(sh) logger.addHandler(fh) # So, a report only counts as safe if both of the following are true: # The levels are either all increasing or all decreasing. # Any two adjacent levels differ by at least one and at most three. def main(): with open("input02.txt", "r", encoding="utf-8") as f: lines = [list(map(int,l.split(" "))) for l in f.readlines()] line_stats = [] for i, line in enumerate(lines): pw_l = list(pairwise(line)) ascending = all([x < y for x,y in pw_l]) descending = all([x > y for x,y in pw_l]) lessthan = all([abs(x - y) <= 3 for x,y in pw_l]) safe = (ascending or descending) and lessthan line_dict = {"ascending": ascending, "descending": descending, "less than 3": lessthan, "safe": (ascending or descending) and lessthan} line_stats.append(line_dict) if i % 5 == 0: logger.info(f"Spot check: {line} is {'' if safe else 'UN'}safe") else: logger.debug(f"{line}: {line_dict}") print(f"Number of safe lines: {sum([1 for s in line_stats if s['safe']])}") if __name__ == "__main__": main()