Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- import sys
- from typing import List
- from typing import Tuple
- from itertools import zip_longest
- from functools import cmp_to_key
- RAN_OUT = -9999999999
- def get_data1(filename: str) -> List[str]:
- with open(filename,'r') as f:
- lines = f.read()
- lines = lines.split("\n\n")
- return lines
- def get_data2(filename: str) -> List[str]:
- with open(filename,'r') as f:
- lines = f.read().splitlines()
- return [l for l in lines if l != '']
- def compare_packets(p1,p2) -> int:
- for v1,v2 in zip_longest(p1,p2,fillvalue=RAN_OUT):
- if v1 == RAN_OUT: return -1
- if v2 == RAN_OUT: return +1
- if type(v1) == int and type(v2) == int:
- if v1 < v2: return -1
- if v1 > v2: return +1
- elif type(v1) == list and type(v2) == list:
- outcome = compare_packets(v1,v2)
- if outcome is not None: return outcome
- elif type(v1) == list and type(v2) == int:
- outcome = compare_packets(v1,[v2])
- if outcome is not None: return outcome
- elif type(v1) == int and type(v2) == list:
- outcome = compare_packets([v1],v2)
- if outcome is not None: return outcome
- else:
- quit(f"Error: Unknown types: v1={type(v1)}, v2={type(v2)}")
- def main():
- # Part 1
- input = get_data1(sys.argv[1])
- part1 = 0
- for ix,pair in enumerate(input):
- parts = pair.split("\n")
- first,second = parts[0], parts[1]
- first = eval(first)
- second = eval(second)
- if compare_packets(first,second) == -1:
- part1 += ix + 1
- print(f"Part 1: {part1}") # 5760
- # Part 2
- input = get_data2(sys.argv[1])
- input.append("[[2]]")
- input.append("[[6]]")
- packets = [eval(p) for p in input]
- packets = sorted(packets, key=cmp_to_key(compare_packets))
- part2 = 1
- for ix,packet in enumerate(packets):
- if packet == [[2]]: part2 *= (ix+1)
- if packet == [[6]]: part2 *= (ix+1)
- print(f"Part 2: {part2}") # 26670
- if __name__=="__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement