|
|
@@ -0,0 +1,73 @@
|
|
|
+import os, argparse
|
|
|
+
|
|
|
+def solve_task(lines):
|
|
|
+ messages = []
|
|
|
+ for line in lines:
|
|
|
+ if line == "":
|
|
|
+ continue
|
|
|
+ else:
|
|
|
+ messages.append(Packet(line))
|
|
|
+
|
|
|
+ d1 = Packet("[[2]]")
|
|
|
+ d2 = Packet("[[6]]")
|
|
|
+ messages.append(d1)
|
|
|
+ messages.append(d2)
|
|
|
+ messages.sort()
|
|
|
+
|
|
|
+ i1 = messages.index(d1)+1
|
|
|
+ i2 = messages.index(d2)+1
|
|
|
+ print(f"Divider packages at index {i1} and {i2}")
|
|
|
+ print(f"Decoder key: {i1*i2}")
|
|
|
+
|
|
|
+class Packet:
|
|
|
+ def __init__(self, line) -> None:
|
|
|
+ self.package = eval(line)
|
|
|
+
|
|
|
+ def __lt__(self, other):
|
|
|
+ return compare(self.package, other.package)
|
|
|
+
|
|
|
+def compare(left,right):
|
|
|
+ if isinstance(left, int) and isinstance(right, int):
|
|
|
+ if left == right:
|
|
|
+ return "undetermined"
|
|
|
+ else:
|
|
|
+ return left < right
|
|
|
+ elif isinstance(left, int):
|
|
|
+ return compare([left], right)
|
|
|
+ elif isinstance(right, int):
|
|
|
+ return compare(left, [right])
|
|
|
+ else:
|
|
|
+ for i in range(min(len(left), len(right))):
|
|
|
+ comp = compare(left[i], right[i])
|
|
|
+ if comp == "undetermined":
|
|
|
+ continue
|
|
|
+ else:
|
|
|
+ return comp
|
|
|
+ if len(left) < len(right):
|
|
|
+ return True
|
|
|
+ elif len(right) < len(left):
|
|
|
+ return False
|
|
|
+ else:
|
|
|
+ return "undetermined"
|
|
|
+
|
|
|
+def read_lines(filename):
|
|
|
+ lines = []
|
|
|
+ with open(filename) as infile:
|
|
|
+ for raw_line in infile:
|
|
|
+ line = raw_line.rstrip()
|
|
|
+ lines.append(line)
|
|
|
+ return lines
|
|
|
+
|
|
|
+def parse_arguments():
|
|
|
+ parser = argparse.ArgumentParser(description="Script that solves the case",epilog="Have a nice day!")
|
|
|
+ parser.add_argument('filename', nargs='?', default="example.txt", help='Input file')
|
|
|
+ args = parser.parse_args()
|
|
|
+ return args
|
|
|
+
|
|
|
+def main():
|
|
|
+ args = parse_arguments()
|
|
|
+ lines = read_lines(args.filename)
|
|
|
+ solve_task(lines)
|
|
|
+
|
|
|
+if __name__ == "__main__":
|
|
|
+ main()
|