#!/bin/python3 import sys,re from pprint import pprint sys.path.insert(0, '../../') from fred import list2int,get_re,nprint,lprint,swap input_f = 'input' part = 2 def loadData(input_f): numbers = [] pages = [] with open(input_f) as file: for line in file: if '|' in line: numbers.append(list2int(line.rstrip().split('|'))) elif ',' in line: pages.append(list2int(line.rstrip().split(','))) else: continue return numbers,pages ######################################### # # # Part 1 # # # ######################################### def getMiddle(line:list): return line[int(len(line)/2)] if part == 1: def checkPages(line:list,numbers:list): #print(line) good = True for ldx,l in enumerate(line): for n in numbers: if n[0] == l: if n[1] in line and n[1] in line[:(ldx)]: good = False #print(n) #print(ldx,l) #print(n[1], line) #print(n[1], line[:(ldx)]) #input() #print(good) #input() if good: return line else: return None numbers = [] pages = [] numbers,pages = loadData(input_f) good = [] result = 0 for lineIdx,line in enumerate(pages): t = checkPages(line,numbers) if t is not None: good.append(t) #nprint(good) # if line not in good: # good.append(line) for i in good: result+=getMiddle(i) print(result) ######################################### # # # Part 2 # # # ######################################### if part == 2: def checkPages(line:list,numbers:list): good = True ldx = 0 while ldx < len(line): for n in numbers: if n[0] == line[ldx]: if n[1] in line and n[1] in line[:(ldx)]: good = False ldx+=1 return line if not good else None def swapBad(numbers,pages): for _ in range(len(pages)): for a,b in numbers: if a in pages and b in pages: ia = pages.index(a) ib = pages.index(b) if ia > ib: pages = swap(ia,ib,pages[:]) return pages numbers = [] pages = [] numbers,pages = loadData(input_f) bad = [] result = 0 for lineIdx,line in enumerate(pages): t = checkPages(line,numbers) if t is not None: bad.append(swapBad(numbers,t)) #print(bad) for i in bad: result+=getMiddle(i) print(result)