101 lines
2.0 KiB
Python
101 lines
2.0 KiB
Python
#!/usr/bin/env python3
|
|
|
|
# a
|
|
# b c
|
|
# d
|
|
# e f
|
|
# g
|
|
|
|
# 1 c f 2
|
|
# 7 a c f 3
|
|
# 4 bcd f 4
|
|
# 2 a cde g 5
|
|
# 3 a cd fg 5
|
|
# 5 ab d fg 5
|
|
# 0 abc efg 6
|
|
# 6 ab defg 6
|
|
# 9 abcd fg 6
|
|
# 8 abcdefg 7
|
|
|
|
# 1 = len(2)
|
|
# 7 = len(3)
|
|
# 4 = len(4)
|
|
# 8 = len(7)
|
|
# b ==cnt(6)
|
|
# e ==cnt(4)
|
|
# bd==4 - 1
|
|
# d ==bd - b
|
|
# 3 = len(5) and len(&1)==2
|
|
# 5 = len(5) & b
|
|
# 2 = len(5) and !3 and !5
|
|
# 9 = len(6) & !e
|
|
# 0 = len(6) & !d
|
|
# 6 = len(6) and !9 and !0
|
|
|
|
# a=7-1
|
|
# f=cnt(9)
|
|
# c=cnt(8) and !a
|
|
# g=cnt(7) and !d
|
|
|
|
# a b c d e f g
|
|
# 8 6 8 7 4 9 7
|
|
from collections import defaultdict, Counter
|
|
|
|
lines = (x.strip() for x in open("input.txt"))
|
|
result = 0
|
|
|
|
for line in lines:
|
|
input, output = tuple(map(lambda x: x.split(), line.split(' | ')))
|
|
numbers = {}
|
|
|
|
# length of the numbers
|
|
lengths = defaultdict(set)
|
|
for x in input:
|
|
lengths[len(x)].add(x)
|
|
|
|
# count the segments
|
|
counts = defaultdict(set)
|
|
for k, v in Counter(''.join(input)).items():
|
|
counts[v].add(k)
|
|
|
|
# easy matching
|
|
numbers[1] = lengths[2].pop()
|
|
numbers[4] = lengths[4].pop()
|
|
numbers[7] = lengths[3].pop()
|
|
numbers[8] = lengths[7].pop()
|
|
|
|
# necessary segment matching
|
|
b = counts[6].pop()
|
|
e = counts[4].pop()
|
|
d = set(numbers[4]).difference(set(numbers[1])).difference({b}).pop()
|
|
|
|
for len5 in lengths[5]:
|
|
# 3
|
|
if len(set(len5).intersection(set(numbers[1]))) == 2:
|
|
numbers[3] = len5
|
|
# 5
|
|
if b in set(len5):
|
|
numbers[5] = len5
|
|
# 2
|
|
numbers[2] = lengths[5].difference({numbers[3], numbers[5]}).pop()
|
|
|
|
for len6 in lengths[6]:
|
|
# 0
|
|
if d not in set(len6):
|
|
numbers[0] = len6
|
|
# 9
|
|
if e not in set(len6):
|
|
numbers[9] = len6
|
|
# 6
|
|
numbers[6] = lengths[6].difference({numbers[0], numbers[9]}).pop()
|
|
|
|
# prepare comparison
|
|
numbers = {''.join(sorted(v)): k for k, v in numbers.items()}
|
|
output = list(''.join(sorted(v)) for v in output)
|
|
|
|
# substitute
|
|
substitute = list(numbers[v] for v in output)
|
|
result += int(''.join(map(str, substitute)))
|
|
|
|
print(result)
|