solution.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #!/usr/bin/python3
  2. import sys
  3. # part 1
  4. def sort_ascii(string):
  5. return ''.join(sorted(string, key = lambda s: (sum(map(ord, s)), s)))
  6. def map_ord(char):
  7. return ord(char) - 96 if ord(char) > 90 else ord(char) - 38
  8. def part1():
  9. total = 0
  10. for line in sys.stdin:
  11. line = line.strip()
  12. left = sort_ascii(line[:len(line)//2])
  13. right = sort_ascii(line[len(line)//2:])
  14. #print(left, right)
  15. l = 0
  16. r = 0
  17. while l < len(left) and r < len(right):
  18. #print(l, left[l], r, right[r])
  19. if left[l] > right[r]:
  20. r += 1
  21. elif right[r] > left[l]:
  22. l += 1
  23. else:
  24. #print(left[l], right[r])
  25. total += map_ord(left[l])
  26. break
  27. pass
  28. print(total)
  29. # part 2
  30. def scan_three_lines():
  31. lines = []
  32. for i, line in enumerate(sys.stdin):
  33. if lines and i % 3 == 0:
  34. yield lines
  35. lines = []
  36. lines.append(line.strip())
  37. if (i + 1) % 3 == 0:
  38. yield lines
  39. def reduce_identical(left, right):
  40. identical = set()
  41. l = 0
  42. r = 0
  43. while l < len(left) and r < len(right):
  44. if left[l] > right[r]:
  45. r += 1
  46. elif right[r] > left[l]:
  47. l += 1
  48. else:
  49. #print(left[l], right[r])
  50. identical.add(left[l])
  51. r += 1
  52. l += 1
  53. return identical
  54. def part2():
  55. total = 0
  56. for l1, l2, l3 in scan_three_lines():
  57. #print(l1, l2, l3)
  58. a1 = reduce_identical(sort_ascii(l1), sort_ascii(l2))
  59. a2 = reduce_identical(sort_ascii(a1), sort_ascii(l3))
  60. #print(a2)
  61. total += map_ord(next(iter(a2)))
  62. print(total)
  63. if sys.argv[1] in '1':
  64. part1()
  65. else:
  66. part2()