12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- #!/usr/bin/python3
- import sys
- # part 1
- def sort_ascii(string):
- return ''.join(sorted(string, key = lambda s: (sum(map(ord, s)), s)))
- def map_ord(char):
- return ord(char) - 96 if ord(char) > 90 else ord(char) - 38
- def part1():
- total = 0
- for line in sys.stdin:
- line = line.strip()
- left = sort_ascii(line[:len(line)//2])
- right = sort_ascii(line[len(line)//2:])
- #print(left, right)
- l = 0
- r = 0
- while l < len(left) and r < len(right):
- #print(l, left[l], r, right[r])
- if left[l] > right[r]:
- r += 1
- elif right[r] > left[l]:
- l += 1
- else:
- #print(left[l], right[r])
- total += map_ord(left[l])
- break
- pass
- print(total)
- # part 2
- def scan_three_lines():
- lines = []
- for i, line in enumerate(sys.stdin):
- if lines and i % 3 == 0:
- yield lines
- lines = []
- lines.append(line.strip())
- if (i + 1) % 3 == 0:
- yield lines
- def reduce_identical(left, right):
- identical = set()
- l = 0
- r = 0
- while l < len(left) and r < len(right):
- if left[l] > right[r]:
- r += 1
- elif right[r] > left[l]:
- l += 1
- else:
- #print(left[l], right[r])
- identical.add(left[l])
- r += 1
- l += 1
- return identical
- def part2():
- total = 0
- for l1, l2, l3 in scan_three_lines():
- #print(l1, l2, l3)
- a1 = reduce_identical(sort_ascii(l1), sort_ascii(l2))
- a2 = reduce_identical(sort_ascii(a1), sort_ascii(l3))
- #print(a2)
- total += map_ord(next(iter(a2)))
- print(total)
- if sys.argv[1] in '1':
- part1()
- else:
- part2()
|