#!/usr/bin/python3 import fileinput from functools import cmp_to_key # Return 1 if the lists are in the right oder, # -1 if the lists are in the wrong order, # 0 if we cannot decide in ths current pass. def ordered(L, R): for i in range(0, len(L)): if i >= len(R): return -1 if type(L[i]) is int and type(R[i]) is int: if L[i] < R[i]: return 1 elif L[i] > R[i]: return -1 elif type(L[i]) is list and type(R[i]) is list: j = ordered(L[i], R[i]) if j != 0: return j elif type(L[i]) is list: j = ordered(L[i], [R[i]]) if j != 0: return j elif type(R[i]) is list: j = ordered([L[i]], R[i]) if j != 0: return j # If we reach this spot, we ran out of items in the left list. if len(L) == len(R): return 0 return 1 packets = [ [[2]], [[6]] ] for line in fileinput.input(): if line.rstrip() == '': continue packets.append(eval(line.rstrip())) # Apparently our cmp function is backwards. The python documentation is # really BAD at explaining how to use custom cmp functions! packets.sort(key=cmp_to_key(ordered), reverse=True) # print('\n'.join([str(i) for i in packets])) product = 1 for i in range(0, len(packets)): if packets[i] == [[2]] or packets[i] == [[6]]: product *= i+1 print(product)