+/AoC
advent of code
git clone https://git.julia.blue/+/AoC
2c992d4
master
1import sys 2import copy 3from functools import reduce 4import string 5import itertools 6from collections import defaultdict ,deque 7 8with open ("input" )as f : 9temp = f .read ().split ("\n\n" ) 10 11p1 = deque (map (int ,temp [0 ].split ()[2 :])) 12p2 = deque (map (int ,temp [1 ].split ()[2 :])) 13 14while p1 and p2 : 15x += 1 16a = p1 .popleft () 17b = p2 .popleft () 18if a > b : 19p1 .append (a ) 20p1 .append (b ) 21else : 22p2 .append (b ) 23p2 .append (a ) 24if not p1 : 25p1 = p2 26 27sum (n * (i + 1 )for i ,n in enumerate (list (p1 )[::- 1 ]))) 28 29sys .exit () 30 31with open ("myinput" )as f : 32temp = f .read ().split ("\n\n" ) 33 34# 0 1 2 3 == right down left up 35 36tiles = set () 37for tile in temp : 38_ ,title ,* data = tile .split () 39n = int (title [:- 1 ]) 40l = len (data [0 ]) 41r = "" .join (data [- i - 1 ][- 1 ]for i in range (l )) 42d = data [- 1 ] 43l = "" .join (data [- i - 1 ][0 ]for i in range (l )) 44u = data [0 ] 45flip = lambda x :x [::- 1 ] 46tiles .add ( 47 ( 48n , 49 (# rotations 50 (r ,d ,l ,u ), 51 (u ,r ,d ,l ), 52 (l ,u ,r ,d ), 53 (d ,l ,u ,r ), 54# flips (along y) 55 (l ,flip (d ),r ,flip (u )), 56 (flip (u ),l ,flip (d ),r ), 57 (r ,flip (u ),l ,flip (d )), 58 (flip (d ),r ,flip (u ),l ), 59# flops (along x) 60 (flip (r ),u ,flip (l ),d ), 61 (d ,flip (r ),u ,flip (l )), 62 (flip (l ),d ,flip (r ),u ), 63 (u ,flip (l ),d ,flip (r )), 64 ), 65 ) 66 ) 67 68corner = None 69total = 1 70for a in sorted (tiles ): 71found = [False ]* 4 72current = a [1 ][0 ] 73for b in tiles : 74if a == b : 75continue 76orientations = b [1 ] 77for o in orientations : 78if o [2 ]== current [0 ]: 79found [0 ]= True 80if o [3 ]== current [1 ]: 81found [1 ]= True 82if o [0 ]== current [2 ]: 83found [2 ]= True 84if o [1 ]== current [3 ]: 85found [3 ]= True 86if sum (found )== 2 : 87if found == [True ,False ,False ,True ]: 88corner = a 89total *= a [0 ] 90 91total ) 92 93 94class Wildcard (object ): 95def __eq__ (self ,other ): 96return True 97 98 99size = int (len (tiles )** 0.5 ) 100 101 102def apply_constraint (board ,tile ,work ,pos ): 103x ,y = pos 104r = range (0 ,size ) 105if (x + 1 ,y )not in board and x + 1 in r : 106if type (work [(x + 1 ,y )][2 ])is str : 107"AHHHH" ) 108sys .exit () 109work [(x + 1 ,y )][2 ]= tile [0 ] 110if (x - 1 ,y )not in board and x - 1 in r : 111if type (work [(x - 1 ,y )][0 ])is str : 112"AHHHH" ) 113sys .exit () 114work [(x - 1 ,y )][0 ]= tile [2 ] 115if (x ,y + 1 )not in board and y + 1 in r : 116if type (work [(x ,y + 1 )][1 ])is str : 117"AHHHH" ) 118sys .exit () 119work [(x ,y + 1 )][1 ]= tile [3 ] 120if (x ,y - 1 )not in board and y - 1 in r : 121if type (work [(x ,y - 1 )][3 ])is str : 122"AHHHH" ) 123sys .exit () 124work [(x ,y - 1 )][3 ]= tile [1 ] 125 126 127def dfs (board ,tiles ,work ): 128if not tiles : 129return board 130if len (tiles )== 1 : 131for k ,v in sorted (board .items ()): 133k ,v ) 134for thing in work .values (): 135i if type (i )is str else None for i in thing ]) 136tiles ) 137# sys.exit() 138# if len(tiles) % 2 == 0: 139# print(" " * (len(tiles) // 2) + "X") 140potential = set (work .keys ()) 141for pos in potential : 142for tile in tiles : 143for o in tile [1 ]: 144if o == tuple (work [pos ]): 145newboard = copy .deepcopy (board ) 146newwork = copy .deepcopy (work ) 147newtiles = copy .deepcopy (tiles ) 148 149newtiles .remove (tile ) 150del newwork [pos ] 151newboard [pos ]= (o ,tile [0 ]) 152apply_constraint (newboard ,o ,newwork ,pos ) 153 154finished = dfs (newboard ,newtiles ,newwork ) 155if finished : 156return finished 157 158 159n ,orientations = corner 160tiles .remove (corner ) 161board = {(0 ,0 ): (orientations [0 ],n )} 162work = defaultdict (lambda : [Wildcard ()]* 4 ) 163apply_constraint (board ,board [(0 ,0 )][0 ],work , (0 ,0 )) 164 165board = dfs (board ,tiles ,work ) 166 167for b in board : 168b ,board [b ][1 ]) 169 170board [(0 ,0 )][1 ] 172* board [(0 ,size - 1 )][1 ] 173* board [(size - 1 ,0 )][1 ] 174* board [(size - 1 ,size - 1 )][1 ] 175) 176 177sys .exit () 178 179with open ("myinput" )as f : 180lines ,messages = f .read ().split ("\n\n" ) 181lines = lines .split ("\n" ) 182messages = messages .split () 183 184stuff = dict () 185for line in lines : 186k ,rest = line .split (":" ) 187k = int (k ) 188rest = rest .split () 189 190if rest [0 ][0 ]== '"' : 191stuff [k ]= str (rest [0 ][1 ]) 192continue 193 194stuff [k ]= [] 195temp = [] 196for current in rest : 197if current == "|" : 198stuff [k ].append (temp ) 199temp = [] 200else : 201temp .append (int (current )) 202stuff [k ].append (temp ) 203 204stuff ) 205messages ) 206 207 208def validate (msg ,rule ,i ): 209i ,msg ,stuff [rule ]) 210if type (stuff [rule ])is str : 211return msg [i ]== rule 212for seq in stuff [rule ]: 213temp = i 214good = True 215for r in seq : 216pass 217# if (i:=validate(msg, )) == -1 218# print(list((msg, r, i + n) for n, r in enumerate(seq))) 219if all (validate (msg ,r ,i + n )for n ,r in enumerate (seq )): 220return True 221return False 222 223 224validate (messages [0 ],0 ,0 )) 225# print(sum(validate(msg, 0, 0) for msg in messages)) 226 227 228sys .exit () 229 230with open ("input" )as f : 231lines = f .readlines () 232 233 234def evaluate (tokens ,lhs ,i ): 235if tokens [i ]== "(" : 236return evalexpr (tokens ,i + 1 ) 237elif tokens [i ]== "+" : 238result ,newi = evaluate (tokens ,lhs ,i + 1 ) 239return lhs + result ,newi 240elif tokens [i ]== "*" : 241result ,newi = evaluate (tokens ,lhs ,i + 1 ) 242while newi < len (tokens )and tokens [newi ]== "+" : 243result ,newi = evaluate (tokens ,result ,newi ) 244return lhs * result ,newi 245else : 246return int (tokens [i ]),i + 1 247 248 249def evalexpr (tokens ,i ): 250acc = 0 251while i < len (tokens )and tokens [i ]!= ")" : 252acc ,i = evaluate (tokens ,acc ,i ) 253return acc ,i + 1 254 255 256tokenize = lambda line :line .replace (")" ," )" ).replace ("(" ,"( " ).split () 257sum (evalexpr (tokenize (line ),0 )[0 ]for line in lines )) 258 259# print(evalexpr(0)[0]) 260 261sys .exit () 262 263with open ("input" )as f : 264lines = enumerate (map (str .strip ,f .readlines ())) 265 266current = set () 267for i ,line in lines : 268for j ,c in enumerate (line ): 269if c == "#" : 270current .add ((0 ,0 ,j ,i )) 271 272 273def adj (pos ): 274x ,y ,z = pos 275return set ( 276 ( 277 (i + x ,j + y ,k + z ) 278for i in range (- 1 ,2 ) 279for j in range (- 1 ,2 ) 280for k in range (- 1 ,2 ) 281if any ((i ,j ,k )) 282 ) 283 ) 284 285 286def adj4 (pos ): 287w ,x ,y ,z = pos 288return set ( 289 ( 290 (h + w ,i + x ,j + y ,k + z ) 291for h in range (- 1 ,2 ) 292for i in range (- 1 ,2 ) 293for j in range (- 1 ,2 ) 294for k in range (- 1 ,2 ) 295if any ((h ,i ,j ,k )) 296 ) 297 ) 298 299 300for _ in range (6 ): 301neighbors = defaultdict (int ) 302for pos in current : 303for n in adj4 (pos ): 304neighbors [n ]+= 1 305 306new_current = set () 307for pos ,n in neighbors .items (): 308if pos in current and 2 == n or n == 3 : 309new_current .add (pos ) 310 311current = new_current 312 313len (current )) 314 315sys .exit () 316 317with open ("input" )as f : 318raw = f .read () 319lines = raw .split ("\n\n" ) 320 321rules = dict () 322kinds = [] 323departure_rules = [] 324for line in lines [0 ].split ("\n" ): 325temp = line .split ("-" ) 326a = temp [0 ].split ()[- 1 ] 327b = temp [1 ].split ()[0 ] 328c = temp [1 ].split ()[- 1 ] 329d = temp [2 ].split ()[0 ] 330kind = temp [0 ].split (":" )[0 ] 331rules [kind ]= (range (int (a ),int (b )+ 1 ),range (int (c ),int (d )+ 1 )) 332kinds .append (kind ) 333if kind .split ()[0 ]== "departure" : 334departure_rules .append (kind ) 335 336flatrules = [r for rule in rules .values ()for r in rule ] 337yours = list (map (int ,lines [1 ].split ()[2 ].split ("," ))) 338nearby = [list (map (int ,x .split ("," )))for x in lines [2 ].split ()[2 :]] 339flatnearby = [n for near in nearby for n in near ] 340 341 342valid_tickets = [] 343total = 0 344for near in nearby : 345rip = False 346for n in near : 347if not any (n in r1 or n in r2 for r1 ,r2 in rules .values ()): 348total += n 349rip = True 350break 351if not rip : 352valid_tickets .append (near ) 353 354total ) 355nearby = valid_tickets 356 357N = range (len (kinds )) 358possibilities = [set (kinds )for _ in N ] 359for near in nearby : 360for k , (r1 ,r2 )in rules .items (): 361for i in N : 362if near [i ]not in r1 and near [i ]not in r2 : 363possibilities [i ].discard (k ) 364 365cantbe = set () 366answers = [0 ]* len (kinds ) 367stuff = sorted (enumerate (possibilities ),key = lambda p :len (p [1 ])) 368for p in stuff : 369i = p [0 ] 370answers [i ]= p [1 ]- cantbe 371cantbe |= answers [i ] 372answers [i ]= answers [i ].pop () 373 374reduce ( 376 (lambda x ,y :x * y ), 377 (yours [i ]for i ,k in enumerate (answers )if k .split ()[0 ]== "departure" ), 378 ) 379) 380 381sys .exit () 382 383stuff = list (map (int ,"8,13,1,0,18,9" .split ("," ))) 384 385current = stuff [- 1 ] 386stuff = {n :i for i ,n in enumerate (stuff [:- 1 ])} 387 388N = 30000000 389for i in range (len (stuff ),N - 1 ): 390# print("turn", i, "- current:", current) 391to_add = current 392if current in stuff : 393# print("current was last seen at", stuff[current]) 394current = i - stuff [current ] 395else : 396current = 0 397stuff [to_add ]= i 398 399current ) 400 401sys .exit () 402 403with open ("input" )as f : 404lines = f .readlines () 405 406setbits = 0 407clearbits = 0 408mem = dict () 409for line in lines : 410comp = line .split () 411if comp [0 ]== "mask" : 412clearbits = ~ int ( 413comp [- 1 ].replace ("1" ,"X" ).replace ("0" ,"1" ).replace ("X" ,"0" ),2 414 ) 415setbits = int (comp [- 1 ].replace ("X" ,"0" ),2 ) 416elif comp [0 ][:3 ]== "mem" : 417addr = int (comp [0 ][4 :- 1 ]) 418temp = int (comp [- 1 ]) 419temp &= clearbits 420temp |= setbits 421mem [addr ]= temp 422 423sum (mem .values ())) 424 425mask = None 426writes = [] 427for line in lines : 428comp = line .split () 429if comp [0 ]== "mask" : 430mask = comp [- 1 ][::- 1 ] 431elif comp [0 ][:3 ]== "mem" : 432addr = int (comp [0 ][4 :- 1 ]) 433finaladdr = [0 ]* 36 434for i in range (36 ): 435if mask [i ]== "1" : 436finaladdr [i ]= "1" 437elif mask [i ]== "X" : 438finaladdr [i ]= "X" 439elif ((addr >> i )& 1 )== 1 : 440finaladdr [i ]= "1" 441else : 442finaladdr [i ]= "0" 443writes .append ((finaladdr [::- 1 ],int (comp [- 1 ]))) 444 445current = writes [- 1 ][0 ] 446actualwrites = [(current [::],writes [- 1 ][1 ])] 447 448# print("writes") 449# for w in writes: 450# print(''.join(w[0]), w[1]) 451# print("\nactual") 452# for w in actualwrites: 453# print(''.join(w[0]), w[1]) 454# print() 455 456for w in writes [- 2 ::- 1 ]: 457some = False 458thismask = w [0 ] 459oldcurrent = current [::] 460count = 0 461for i in range (36 ): 462if current [i ]== "1" and thismask [i ]!= "1" : 463count += 1 464current [i ]= "X" 465some = True 466if thismask [i ]== "X" : 467thismask [i ]= "0" 468elif current [i ]== "0" and thismask [i ]!= "0" : 469count += 1 470current [i ]= "X" 471some = True 472if thismask [i ]== "X" : 473thismask [i ]= "1" 474if some : 475"current" ,"" .join (oldcurrent )) 476"this " ,"" .join (thismask )) 477count ,"\n" ) 478actualwrites .append ((thismask [::],w [1 ])) 479 480for w in actualwrites : 481"" .join (w [0 ]),w [1 ]) 482 483sum (2 ** addr .count ("X" )* val for addr ,val in actualwrites )) 484 485sys .exit () 486 487with open ("input" )as f : 488first ,second = f .readlines () 489 490earliest = int (first ) 491busses = [int (x )for x in second .split ("," )if x != "x" ] 492 493 494def solvea (): 495i = earliest 496while True : 497for b in busses : 498if i % b == 0 : 499b * (i - earliest )) 500return 501i += 1 502 503 504solvea () 505 506busses = [(int (x ),n )for n ,x in enumerate (second .split ("," ))if x != "x" ] 507# print(busses) 508# sys.exit() 509for i in range (len (busses )): 510busses [i ]= busses [i ][0 ], (busses [i ][0 ]* 2 - busses [i ][1 ])% busses [i ][0 ] 511 512busses ) 513 514bus ,off = list (zip (* busses )) 515bus ,off ) 516 517 518def extended_eucalid (a ,b ): 519x ,y ,u ,v = 0 ,1 ,1 ,0 520while a != 0 : 521q ,r = b // a ,b % a 522m ,n = x - u * q ,y - v * q 523b ,a ,x ,y ,u ,v = a ,r ,u ,v ,m ,n 524return x ,y 525 526 527def crt_solve_for_x (off ,bus ): 528terms = len (off ) 529constants = [1 ]* terms 530product = reduce ((lambda x ,y :x * y ),bus ) 531 532for i in range (terms ): 533other_prod = product // bus [i ] 534eucalid_result = extended_eucalid (other_prod ,bus [i ])[0 ] 535if eucalid_result < 0 : 536eucalid_result += bus [i ] 537constants [i ]= other_prod * eucalid_result * off [i ] 538 539return sum (constants )% product ,product 540 541 542crt_solve_for_x ([0 ,3 ,4 ], [3 ,4 ,5 ]))# should = 39 543 544from math import gcd 545 546for i in bus : 547for j in bus : 548if i != j and gcd (i ,j )!= 1 : 549"NOPE" ,i ,j ) 550sys .exit ()# they're all coprime 551 552crt_solve_for_x (off ,bus )) 553 554sys .exit () 555 556with open ("input" )as f : 557lines = f .readlines () 558 559d = 0 560directions = ["E" ,"S" ,"W" ,"N" ] 561x = 0 562y = 0 563for line in lines : 564command ,amount = line [0 ],int (line [1 :]) 565if command == "F" : 566command = directions [d ] 567 568if command == "R" : 569d = (d + amount // 90 )% 4 570elif command == "L" : 571d = (d + 4 - amount // 90 )% 4 572elif command == "N" : 573y += amount 574elif command == "S" : 575y -= amount 576elif command == "E" : 577x += amount 578elif command == "W" : 579x -= amount 580 581abs (x )+ abs (y )) 582 583x = y = 0 584wx = 10 585wy = - 1 586for line in lines : 587command ,amount = line [0 ],int (line [1 :]) 588if command == "L" : 589command = "R" 590amount = 360 - amount 591# print(x, y, "waypoint", wx, wy) 592# print(command, amount) 593 594if command == "F" : 595x += wx * amount 596y += wy * amount 597elif command == "R" : 598# print(wx, wy) 599for _ in range (amount // 90 ): 600 (wx ,wy )= (- wy ,wx ) 601# print(wx, wy) 602# print() 603elif command == "N" : 604wy -= amount 605elif command == "S" : 606wy += amount 607elif command == "E" : 608wx += amount 609elif command == "W" : 610wx -= amount 611 612abs (x )+ abs (y )) 613 614sys .exit () 615 616with open ("input" )as f : 617grid = list (map (lambda x :list (x .strip ()),f .readlines ())) 618 619h = len (grid [0 ]) 620w = len (grid ) 621 622 623def neighbors (x ,y ,g ): 624directions = set (itertools .product (range (- 1 ,2 ),range (- 1 ,2 ))) 625directions .discard ((0 ,0 )) 626result = set () 627for (xi ,yi )in directions : 628newx = max (min (w - 1 ,x + xi ),0 ) 629newy = max (min (h - 1 ,y + yi ),0 ) 630result .add ((newx ,newy )) 631result .discard ((x ,y )) 632return sum (g [j ][k ]== "#" for (j ,k )in result ) 633 634 635def extended_neighbors (x ,y ,g ): 636directions = set (itertools .product (range (- 1 ,2 ),range (- 1 ,2 ))) 637directions .discard ((0 ,0 )) 638total = 0 639for (xi ,yi )in directions : 640 (cx ,cy )= (x ,y ) 641while True : 642cx += xi 643cy += yi 644if cx not in range (0 ,w )or cy not in range (0 ,h )or g [cx ][cy ]== "L" : 645break 646if g [cx ][cy ]== "#" : 647total += 1 648break 649 650return total 651 652 653def printgrid (g ): 654for row in g : 655"" .join (row )) 656"\n" ) 657 658 659temp = copy .deepcopy (grid ) 660 661while True : 662changed = False 663for x in range (w ): 664for y in range (h ): 665current = grid [x ][y ] 666total = extended_neighbors (x ,y ,grid ) 667if current == "L" and total == 0 : 668temp [x ][y ]= "#" 669changed = True 670elif current == "#" and total >= 5 : 671temp [x ][y ]= "L" 672changed = True 673# printgrid(grid) 674if not changed : 675break 676grid = copy .deepcopy (temp ) 677 678sum (sum (x == "#" for x in row )for row in grid )) 679 680sys .exit () 681 682with open ("input" )as f : 683l = list (map (int ,f .readlines ())) 684 685dist = 25 686target = None 687for i in range (dist ,len (l )): 688before = l [i - dist :i ] 689subs = [l [i ]- n for n in before ] 690if not any (n in subs for n in before ): 691target = l [i ] 692break 693 694target ) 695 696i = 0 697j = 0 698total = l [0 ] 699while True : 700if total == target : 701r = l [i :j + 1 ] 702max (r )+ min (r )) 703sys .exit () 704 705while total < target : 706j += 1 707total += l [j ] 708 709while total > target : 710total -= l [i ] 711i += 1 712 713 714sys .exit () 715 716with open ("input" )as f : 717l = [0 ]+ sorted (map (int ,f .readlines ())) 718l += [l [- 1 ]+ 3 ] 719 720diffs = [0 ,0 ,0 ] 721for i in range (len (l )- 1 ): 722diff = l [i + 1 ]- l [i ] 723diffs [diff - 1 ]+= 1 724 725diffs [0 ]* diffs [2 ]) 726 727memo = {n :None for n in l } 728memo [l [- 1 ]]= 1 729 730 731def calculate (n ): 732if n not in memo : 733return 0 734if not memo [n ]: 735memo [n ]= calculate (n + 1 )+ calculate (n + 2 )+ calculate (n + 3 ) 736return memo [n ] 737 738 739calculate (0 )) 740 741sys .exit () 742 743with open ("input" )as f : 744lines = list (enumerate (map (str .split ,f .readlines ()))) 745 746pc = 0 747acc = 0 748seen = set () 749 750while True : 751if pc in seen : 752pc ,acc ) 753break 754seen .add (pc ) 755ins = lines [pc ][1 ][0 ] 756if ins == "jmp" : 757pc += int (lines [pc ][1 ][1 ]) 758else : 759if ins == "acc" : 760acc += int (lines [pc ][1 ][1 ]) 761pc += 1 762 763 764def check (newlines ): 765pc = 0 766acc = 0 767seen = set () 768target = len (newlines ) 769 770while pc < target : 771if pc in seen : 772return 773seen .add (pc ) 774ins = newlines [pc ][1 ][0 ] 775if ins == "jmp" : 776pc += int (newlines [pc ][1 ][1 ]) 777else : 778if ins == "acc" : 779acc += int (newlines [pc ][1 ][1 ]) 780pc += 1 781 782pc ,acc ) 783sys .exit () 784 785 786for i in range (len (lines )): 787ins = lines [i ][1 ][0 ] 788if ins == "nop" : 789newlines = copy .deepcopy (lines ) 790newlines [i ][1 ][0 ]= "jmp" 791check (newlines ) 792elif ins == "jmp" : 793newlines = copy .deepcopy (lines ) 794newlines [i ][1 ][0 ]= "nop" 795check (newlines ) 796 797"didnt find" ) 798 799sys .exit () 800 801with open ("input" )as f : 802lines = list (map (str .strip ,f .readlines ())) 803 804parents = defaultdict (list ) 805children = defaultdict (list ) 806for line in lines : 807words = line .split () 808current = " " .join (words [0 :2 ]) 809if len (words )== 7 : 810children [current ]= 1 811continue 812for i in range (4 ,len (words ),4 ): 813children [current ].append ((" " .join (words [i + 1 :i + 3 ]),int (words [i ]))) 814parents [(" " .join (words [i + 1 :i + 3 ]))].append ( 815 (current ,int (words [i ])), 816 ) 817 818contain = set (i [0 ]for i in parents ["shiny gold" ]) 819 820old_size = len (contain ) 821new_size = 0 822 823while old_size != new_size : 824new_size = old_size 825to_add = set () 826for name in contain : 827for parent in parents [name ]: 828to_add .add (parent [0 ]) 829contain |= to_add 830old_size = len (contain ) 831 832len (contain )) 833 834 835def count_children (name ): 836name ,"\t" ,children [name ]) 837if children [name ]== 1 : 838return 1 839return 1 + sum (n * count_children (s )for s ,n in children [name ]) 840 841 842count_children ("shiny gold" )- 1 ) 843sys .exit () 844 845with open ("input" )as f : 846raw = f .read () 847sum (len (set (group .replace ("\n" ,"" )))for group in raw .split ("\n\n" ))) 848sum (len (set .intersection (* map (set ,line .split ())))for line in raw .split ("\n\n" ))) 849 850sys .exit () 851 852with open ("input" )as f : 853stuff = map (str .strip ,f .readlines ()) 854 855ids = set () 856for line in stuff : 857fb = line [:7 ].replace ("F" ,"0" ).replace ("B" ,"1" ) 858lr = line [7 :].replace ("L" ,"0" ).replace ("R" ,"1" ) 859ids .add (int (fb ,2 )* 8 + int (lr ,2 )) 860 861possible = set () 862for i in range (1 ,127 ): 863for j in range (8 ): 864possible .add (i * 8 + j ) 865 866len (possible ),len (ids )) 867max (ids )) 868possible - ids ) 869sys .exit () 870 871with open ("input" )as f : 872raw = f .read () 873lines = raw .split ("\n\n" ) 874passports = [dict (elem .split (":" )for elem in line .split ())for line in lines ] 875 876 877fields = ("byr" ,"iyr" ,"eyr" ,"hgt" ,"hcl" ,"ecl" ,"pid" ) 878 879# def verify(port): 880# return all(f in port for f in fields) 881 882 883def verify (port ): 884if not all (f in port for f in fields ): 885return False 886year = port ["byr" ] 887if not year .isdigit ()or not 1920 <= int (year )<= 2002 : 888return False 889year = port ["iyr" ] 890if not year .isdigit ()or not 2010 <= int (year )<= 2020 : 891return False 892year = port ["eyr" ] 893if not year .isdigit ()or not 2020 <= int (year )<= 2030 : 894return False 895height = port ["hgt" ] 896if height [- 2 :]== "in" : 897n = height [:- 2 ] 898if not n .isdigit ()or not 59 <= int (n )<= 76 : 899return False 900elif height [- 2 :]== "cm" : 901n = height [:- 2 ] 902if not n .isdigit ()or not 150 <= int (n )<= 193 : 903return False 904else : 905return False 906hair = port ["hcl" ] 907if ( 908hair [0 ]!= "#" 909or len (hair )!= 7 910or not all (c in string .hexdigits for c in hair [1 :]) 911 ): 912return False 913if port ["ecl" ]not in ("amb" ,"blu" ,"brn" ,"gry" ,"grn" ,"hzl" ,"oth" ): 914return False 915if len (port ["pid" ])!= 9 or not port ["pid" ].isdigit (): 916return False 917return True 918 919 920sum ((verify (x )for x in passports ))) 921sys .exit () 922 923dots = [[1 if c == "." else 0 for c in line ]for line in lines ] 924 925 926def traverse (right ,down ): 927x = 0 928y = 0 929count = 0 930while y < len (dots ): 931count += not (dots [y ][x ]) 932x += right 933x %= len (dots [0 ]) 934y += down 935return count 936 937 938# print() 939# for row in dots: 940# print("".join(map(str, row))) 941# print(dots) 942# print() 943 944# print(sum(n.count('#') for n in dots)) 945 946# print(traverse(3, 1)) 947traverse (1 ,1 )* traverse (3 ,1 )* traverse (5 ,1 )* traverse (7 ,1 )* traverse (1 ,2 ) 949) 950 951import sys 952 953sys .exit () 954count = 0 955 956for line in lines : 957temp = line .split () 958least ,most = map (int ,temp [0 ].split ("-" )) 959target = temp [1 ][0 ] 960least ,most ,target ) 961pw = temp [2 ] 962if ( 963pw [least - 1 ]== target 964and pw [most - 1 ]!= target 965or pw [least - 1 ]!= target 966and pw [most - 1 ]== target 967 ): 968count += 1 969# if least <= temp[2].count(target) <= most: 970# count += 1 971 972count )